repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.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
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Formatting
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
Partial Friend Class TriviaDataFactory
''' <summary>
''' represents a general trivia between two tokens. slightly more expensive than others since it
''' needs to calculate stuff unlike other cases
''' </summary>
Private Class LineContinuationTrivia
Inherits AbstractLineBreakTrivia
Public Sub New(options As AnalyzerConfigOptions,
originalString As String,
indentation As Integer)
MyBase.New(options, originalString, 1, indentation, False)
End Sub
Protected Overrides Function CreateStringFromState() As String
Contract.ThrowIfFalse(Me.SecondTokenIsFirstTokenOnLine)
Dim builder = StringBuilderPool.Allocate()
builder.Append(" "c)
builder.Append(SyntaxFacts.GetText(SyntaxKind.LineContinuationTrivia))
builder.AppendIndentationString(Me.Spaces, Me.Options.GetOption(FormattingOptions2.UseTabs), Me.Options.GetOption(FormattingOptions2.TabSize))
Return StringBuilderPool.ReturnAndFree(builder)
End Function
Public Overrides Function WithIndentation(indentation As Integer,
context As FormattingContext,
formattingRules As ChainedFormattingRules,
cancellationToken As CancellationToken) As TriviaData
If Me.Spaces = indentation Then
Return Me
End If
Return New LineContinuationTrivia(Me.Options, Me._original, indentation)
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Formatting
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
Partial Friend Class TriviaDataFactory
''' <summary>
''' represents a general trivia between two tokens. slightly more expensive than others since it
''' needs to calculate stuff unlike other cases
''' </summary>
Private Class LineContinuationTrivia
Inherits AbstractLineBreakTrivia
Public Sub New(options As AnalyzerConfigOptions,
originalString As String,
indentation As Integer)
MyBase.New(options, originalString, 1, indentation, False)
End Sub
Protected Overrides Function CreateStringFromState() As String
Contract.ThrowIfFalse(Me.SecondTokenIsFirstTokenOnLine)
Dim builder = StringBuilderPool.Allocate()
builder.Append(" "c)
builder.Append(SyntaxFacts.GetText(SyntaxKind.LineContinuationTrivia))
builder.AppendIndentationString(Me.Spaces, Me.Options.GetOption(FormattingOptions2.UseTabs), Me.Options.GetOption(FormattingOptions2.TabSize))
Return StringBuilderPool.ReturnAndFree(builder)
End Function
Public Overrides Function WithIndentation(indentation As Integer,
context As FormattingContext,
formattingRules As ChainedFormattingRules,
cancellationToken As CancellationToken) As TriviaData
If Me.Spaces = indentation Then
Return Me
End If
Return New LineContinuationTrivia(Me.Options, Me._original, indentation)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceSymbolHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Module SourceSymbolHelpers
Public Function GetAsClauseLocation(identifier As SyntaxToken, asClauseOpt As AsClauseSyntax) As SyntaxNodeOrToken
If asClauseOpt IsNot Nothing AndAlso
(asClauseOpt.Kind <> SyntaxKind.AsNewClause OrElse
(DirectCast(asClauseOpt, AsNewClauseSyntax).NewExpression.Kind <> SyntaxKind.AnonymousObjectCreationExpression)) Then
Return asClauseOpt.Type
Else
Return identifier
End If
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Module SourceSymbolHelpers
Public Function GetAsClauseLocation(identifier As SyntaxToken, asClauseOpt As AsClauseSyntax) As SyntaxNodeOrToken
If asClauseOpt IsNot Nothing AndAlso
(asClauseOpt.Kind <> SyntaxKind.AsNewClause OrElse
(DirectCast(asClauseOpt, AsNewClauseSyntax).NewExpression.Kind <> SyntaxKind.AnonymousObjectCreationExpression)) Then
Return asClauseOpt.Type
Else
Return identifier
End If
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/VisualStudio/Core/Def/EditorConfigSettings/Whitespace/ViewModel/TabSizeViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel
{
internal class TabSizeViewModel : EnumSettingViewModel<TabSizeSettings>
{
private readonly WhitespaceSetting _setting;
public TabSizeViewModel(WhitespaceSetting setting)
{
_setting = setting;
}
protected override void ChangePropertyTo(TabSizeSettings newValue)
=> _setting.SetValue((int)newValue);
protected override TabSizeSettings GetCurrentValue()
{
return _setting.GetValue() switch
{
1 => TabSizeSettings._1,
2 => TabSizeSettings._2,
3 => TabSizeSettings._3,
4 => TabSizeSettings._4,
5 => TabSizeSettings._5,
6 => TabSizeSettings._6,
7 => TabSizeSettings._7,
_ => TabSizeSettings._8,
};
}
protected override IReadOnlyDictionary<string, TabSizeSettings> GetValuesAndDescriptions()
{
return EnumerateOptions().ToDictionary(x => x.description, x => x.value);
static IEnumerable<(string description, TabSizeSettings value)> EnumerateOptions()
{
yield return ("1", TabSizeSettings._1);
yield return ("2", TabSizeSettings._2);
yield return ("3", TabSizeSettings._3);
yield return ("4", TabSizeSettings._4);
yield return ("5", TabSizeSettings._5);
yield return ("6", TabSizeSettings._6);
yield return ("7", TabSizeSettings._7);
yield return ("8", TabSizeSettings._8);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel
{
internal class TabSizeViewModel : EnumSettingViewModel<TabSizeSettings>
{
private readonly WhitespaceSetting _setting;
public TabSizeViewModel(WhitespaceSetting setting)
{
_setting = setting;
}
protected override void ChangePropertyTo(TabSizeSettings newValue)
=> _setting.SetValue((int)newValue);
protected override TabSizeSettings GetCurrentValue()
{
return _setting.GetValue() switch
{
1 => TabSizeSettings._1,
2 => TabSizeSettings._2,
3 => TabSizeSettings._3,
4 => TabSizeSettings._4,
5 => TabSizeSettings._5,
6 => TabSizeSettings._6,
7 => TabSizeSettings._7,
_ => TabSizeSettings._8,
};
}
protected override IReadOnlyDictionary<string, TabSizeSettings> GetValuesAndDescriptions()
{
return EnumerateOptions().ToDictionary(x => x.description, x => x.value);
static IEnumerable<(string description, TabSizeSettings value)> EnumerateOptions()
{
yield return ("1", TabSizeSettings._1);
yield return ("2", TabSizeSettings._2);
yield return ("3", TabSizeSettings._3);
yield return ("4", TabSizeSettings._4);
yield return ("5", TabSizeSettings._5);
yield return ("6", TabSizeSettings._6);
yield return ("7", TabSizeSettings._7);
yield return ("8", TabSizeSettings._8);
}
}
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.tr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../WorkspaceDesktopResources.resx">
<body>
<trans-unit id="Invalid_assembly_name">
<source>Invalid assembly name</source>
<target state="translated">Geçersiz derleme adı</target>
<note />
</trans-unit>
<trans-unit id="Invalid_characters_in_assembly_name">
<source>Invalid characters in assembly name</source>
<target state="translated">Derleme adında geçersiz karakterler</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="tr" original="../WorkspaceDesktopResources.resx">
<body>
<trans-unit id="Invalid_assembly_name">
<source>Invalid assembly name</source>
<target state="translated">Geçersiz derleme adı</target>
<note />
</trans-unit>
<trans-unit id="Invalid_characters_in_assembly_name">
<source>Invalid characters in assembly name</source>
<target state="translated">Derleme adında geçersiz karakterler</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeFunction.IMethodXML.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
public partial class CodeFunction
{
public string GetXML()
{
using (Logger.LogBlock(FunctionId.WinformDesigner_GenerateXML, CancellationToken.None))
{
return CodeModelService.GetMethodXml(LookupNode(), GetSemanticModel());
}
}
public int SetXML(string bstrXML)
{
// This doesn't need to be implemented since nothing in VS currently uses it.
throw new NotImplementedException();
}
public int GetBodyPoint(out object ppUnk)
=> throw new NotImplementedException();
object IMethodXML2.GetXML()
=> new StringReader(GetXML());
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
public partial class CodeFunction
{
public string GetXML()
{
using (Logger.LogBlock(FunctionId.WinformDesigner_GenerateXML, CancellationToken.None))
{
return CodeModelService.GetMethodXml(LookupNode(), GetSemanticModel());
}
}
public int SetXML(string bstrXML)
{
// This doesn't need to be implemented since nothing in VS currently uses it.
throw new NotImplementedException();
}
public int GetBodyPoint(out object ppUnk)
=> throw new NotImplementedException();
object IMethodXML2.GetXML()
=> new StringReader(GetXML());
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Compilers/VisualBasic/Portable/Generated/BoundNodes.xml.Generated.vb | ' <auto-generated />
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Runtime.CompilerServices
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Enum BoundKind as Byte
TypeArguments
OmittedArgument
LValueToRValueWrapper
WithLValueExpressionPlaceholder
WithRValueExpressionPlaceholder
RValuePlaceholder
LValuePlaceholder
Dup
BadExpression
BadStatement
Parenthesized
BadVariable
ArrayAccess
ArrayLength
[GetType]
FieldInfo
MethodInfo
TypeExpression
TypeOrValueExpression
NamespaceExpression
MethodDefIndex
MaximumMethodDefIndex
InstrumentationPayloadRoot
ModuleVersionId
ModuleVersionIdString
SourceDocumentIndex
UnaryOperator
UserDefinedUnaryOperator
NullableIsTrueOperator
BinaryOperator
UserDefinedBinaryOperator
UserDefinedShortCircuitingOperator
CompoundAssignmentTargetPlaceholder
AssignmentOperator
ReferenceAssignment
AddressOfOperator
TernaryConditionalExpression
BinaryConditionalExpression
Conversion
RelaxationLambda
ConvertedTupleElements
UserDefinedConversion
[DirectCast]
[TryCast]
[TypeOf]
SequencePoint
SequencePointExpression
SequencePointWithSpan
NoOpStatement
MethodGroup
PropertyGroup
ReturnStatement
YieldStatement
ThrowStatement
RedimStatement
RedimClause
EraseStatement
[Call]
Attribute
LateMemberAccess
LateInvocation
LateAddressOfOperator
TupleLiteral
ConvertedTupleLiteral
ObjectCreationExpression
NoPiaObjectCreationExpression
AnonymousTypeCreationExpression
AnonymousTypePropertyAccess
AnonymousTypeFieldInitializer
ObjectInitializerExpression
CollectionInitializerExpression
NewT
DelegateCreationExpression
ArrayCreation
ArrayLiteral
ArrayInitialization
FieldAccess
PropertyAccess
EventAccess
Block
StateMachineScope
LocalDeclaration
AsNewLocalDeclarations
DimStatement
Initializer
FieldInitializer
PropertyInitializer
ParameterEqualsValue
GlobalStatementInitializer
Sequence
ExpressionStatement
IfStatement
SelectStatement
CaseBlock
CaseStatement
SimpleCaseClause
RangeCaseClause
RelationalCaseClause
DoLoopStatement
WhileStatement
ForToUserDefinedOperators
ForToStatement
ForEachStatement
ExitStatement
ContinueStatement
TryStatement
CatchBlock
Literal
MeReference
ValueTypeMeReference
MyBaseReference
MyClassReference
PreviousSubmissionReference
HostObjectMemberReference
Local
PseudoVariable
Parameter
ByRefArgumentPlaceholder
ByRefArgumentWithCopyBack
LateBoundArgumentSupportingAssignmentWithCapture
LabelStatement
Label
GotoStatement
StatementList
ConditionalGoto
WithStatement
UnboundLambda
Lambda
QueryExpression
QuerySource
ToQueryableCollectionConversion
QueryableSource
QueryClause
Ordering
QueryLambda
RangeVariableAssignment
GroupTypeInferenceLambda
AggregateClause
GroupAggregation
RangeVariable
AddHandlerStatement
RemoveHandlerStatement
RaiseEventStatement
UsingStatement
SyncLockStatement
XmlName
XmlNamespace
XmlDocument
XmlDeclaration
XmlProcessingInstruction
XmlComment
XmlAttribute
XmlElement
XmlMemberAccess
XmlEmbeddedExpression
XmlCData
ResumeStatement
OnErrorStatement
UnstructuredExceptionHandlingStatement
UnstructuredExceptionHandlingCatchFilter
UnstructuredExceptionOnErrorSwitch
UnstructuredExceptionResumeSwitch
AwaitOperator
SpillSequence
StopStatement
EndStatement
MidResult
ConditionalAccess
ConditionalAccessReceiverPlaceholder
LoweredConditionalAccess
ComplexConditionalAccessReceiver
NameOfOperator
TypeAsValueExpression
InterpolatedStringExpression
Interpolation
End Enum
Partial Friend MustInherit Class BoundExpression
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
Me._Type = type
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax)
Me._Type = type
End Sub
Private ReadOnly _Type As TypeSymbol
Public ReadOnly Property Type As TypeSymbol
Get
Return _Type
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundTypeArguments
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, arguments As ImmutableArray(Of TypeSymbol), hasErrors As Boolean)
MyBase.New(BoundKind.TypeArguments, syntax, Nothing, hasErrors)
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Arguments = arguments
End Sub
Public Sub New(syntax As SyntaxNode, arguments As ImmutableArray(Of TypeSymbol))
MyBase.New(BoundKind.TypeArguments, syntax, Nothing)
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Arguments = arguments
End Sub
Private ReadOnly _Arguments As ImmutableArray(Of TypeSymbol)
Public ReadOnly Property Arguments As ImmutableArray(Of TypeSymbol)
Get
Return _Arguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeArguments(Me)
End Function
Public Function Update(arguments As ImmutableArray(Of TypeSymbol)) As BoundTypeArguments
If arguments <> Me.Arguments Then
Dim result = New BoundTypeArguments(Me.Syntax, arguments, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundOmittedArgument
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.OmittedArgument, syntax, type, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.OmittedArgument, syntax, type)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitOmittedArgument(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundOmittedArgument
If type IsNot Me.Type Then
Dim result = New BoundOmittedArgument(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundValuePlaceholderBase
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundLValueToRValueWrapper
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, underlyingLValue As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LValueToRValueWrapper, syntax, type, hasErrors OrElse underlyingLValue.NonNullAndHasErrors())
Debug.Assert(underlyingLValue IsNot Nothing, "Field 'underlyingLValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingLValue = underlyingLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _UnderlyingLValue As BoundExpression
Public ReadOnly Property UnderlyingLValue As BoundExpression
Get
Return _UnderlyingLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLValueToRValueWrapper(Me)
End Function
Public Function Update(underlyingLValue As BoundExpression, type As TypeSymbol) As BoundLValueToRValueWrapper
If underlyingLValue IsNot Me.UnderlyingLValue OrElse type IsNot Me.Type Then
Dim result = New BoundLValueToRValueWrapper(Me.Syntax, underlyingLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundLValuePlaceholderBase
Inherits BoundValuePlaceholderBase
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend MustInherit Class BoundRValuePlaceholderBase
Inherits BoundValuePlaceholderBase
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundWithLValueExpressionPlaceholder
Inherits BoundLValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.WithLValueExpressionPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.WithLValueExpressionPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWithLValueExpressionPlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundWithLValueExpressionPlaceholder
If type IsNot Me.Type Then
Dim result = New BoundWithLValueExpressionPlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundWithRValueExpressionPlaceholder
Inherits BoundRValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.WithRValueExpressionPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.WithRValueExpressionPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWithRValueExpressionPlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundWithRValueExpressionPlaceholder
If type IsNot Me.Type Then
Dim result = New BoundWithRValueExpressionPlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRValuePlaceholder
Inherits BoundRValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.RValuePlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.RValuePlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRValuePlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundRValuePlaceholder
If type IsNot Me.Type Then
Dim result = New BoundRValuePlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLValuePlaceholder
Inherits BoundLValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.LValuePlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.LValuePlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLValuePlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundLValuePlaceholder
If type IsNot Me.Type Then
Dim result = New BoundLValuePlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDup
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, isReference As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Dup, syntax, type, hasErrors)
Me._IsReference = isReference
End Sub
Public Sub New(syntax As SyntaxNode, isReference As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.Dup, syntax, type)
Me._IsReference = isReference
End Sub
Private ReadOnly _IsReference As Boolean
Public ReadOnly Property IsReference As Boolean
Get
Return _IsReference
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDup(Me)
End Function
Public Function Update(isReference As Boolean, type As TypeSymbol) As BoundDup
If isReference <> Me.IsReference OrElse type IsNot Me.Type Then
Dim result = New BoundDup(Me.Syntax, isReference, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBadExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, resultKind As LookupResultKind, symbols As ImmutableArray(Of Symbol), childBoundNodes As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BadExpression, syntax, type, hasErrors OrElse childBoundNodes.NonNullAndHasErrors())
Debug.Assert(Not (symbols.IsDefault), "Field 'symbols' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (childBoundNodes.IsDefault), "Field 'childBoundNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ResultKind = resultKind
Me._Symbols = symbols
Me._ChildBoundNodes = childBoundNodes
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
Private ReadOnly _Symbols As ImmutableArray(Of Symbol)
Public ReadOnly Property Symbols As ImmutableArray(Of Symbol)
Get
Return _Symbols
End Get
End Property
Private ReadOnly _ChildBoundNodes As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ChildBoundNodes As ImmutableArray(Of BoundExpression)
Get
Return _ChildBoundNodes
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBadExpression(Me)
End Function
Public Function Update(resultKind As LookupResultKind, symbols As ImmutableArray(Of Symbol), childBoundNodes As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundBadExpression
If resultKind <> Me.ResultKind OrElse symbols <> Me.Symbols OrElse childBoundNodes <> Me.ChildBoundNodes OrElse type IsNot Me.Type Then
Dim result = New BoundBadExpression(Me.Syntax, resultKind, symbols, childBoundNodes, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBadStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, childBoundNodes As ImmutableArray(Of BoundNode), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BadStatement, syntax, hasErrors OrElse childBoundNodes.NonNullAndHasErrors())
Debug.Assert(Not (childBoundNodes.IsDefault), "Field 'childBoundNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ChildBoundNodes = childBoundNodes
End Sub
Private ReadOnly _ChildBoundNodes As ImmutableArray(Of BoundNode)
Public ReadOnly Property ChildBoundNodes As ImmutableArray(Of BoundNode)
Get
Return _ChildBoundNodes
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBadStatement(Me)
End Function
Public Function Update(childBoundNodes As ImmutableArray(Of BoundNode)) As BoundBadStatement
If childBoundNodes <> Me.ChildBoundNodes Then
Dim result = New BoundBadStatement(Me.Syntax, childBoundNodes, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundParenthesized
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Parenthesized, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitParenthesized(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundParenthesized
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundParenthesized(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBadVariable
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, isLValue As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BadVariable, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Me._IsLValue = isLValue
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBadVariable(Me)
End Function
Public Function Update(expression As BoundExpression, isLValue As Boolean, type As TypeSymbol) As BoundBadVariable
If expression IsNot Me.Expression OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundBadVariable(Me.Syntax, expression, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, indices As ImmutableArray(Of BoundExpression), isLValue As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayAccess, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors() OrElse indices.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (indices.IsDefault), "Field 'indices' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Me._Indices = indices
Me._IsLValue = isLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _Indices As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Indices As ImmutableArray(Of BoundExpression)
Get
Return _Indices
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayAccess(Me)
End Function
Public Function Update(expression As BoundExpression, indices As ImmutableArray(Of BoundExpression), isLValue As Boolean, type As TypeSymbol) As BoundArrayAccess
If expression IsNot Me.Expression OrElse indices <> Me.Indices OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundArrayAccess(Me.Syntax, expression, indices, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayLength
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayLength, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayLength(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundArrayLength
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundArrayLength(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGetType
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, sourceType As BoundTypeExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GetType, syntax, type, hasErrors OrElse sourceType.NonNullAndHasErrors())
Debug.Assert(sourceType IsNot Nothing, "Field 'sourceType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._SourceType = sourceType
End Sub
Private ReadOnly _SourceType As BoundTypeExpression
Public ReadOnly Property SourceType As BoundTypeExpression
Get
Return _SourceType
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGetType(Me)
End Function
Public Function Update(sourceType As BoundTypeExpression, type As TypeSymbol) As BoundGetType
If sourceType IsNot Me.SourceType OrElse type IsNot Me.Type Then
Dim result = New BoundGetType(Me.Syntax, sourceType, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundFieldInfo
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, field As FieldSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.FieldInfo, syntax, type, hasErrors)
Debug.Assert(field IsNot Nothing, "Field 'field' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Field = field
End Sub
Public Sub New(syntax As SyntaxNode, field As FieldSymbol, type As TypeSymbol)
MyBase.New(BoundKind.FieldInfo, syntax, type)
Debug.Assert(field IsNot Nothing, "Field 'field' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Field = field
End Sub
Private ReadOnly _Field As FieldSymbol
Public ReadOnly Property Field As FieldSymbol
Get
Return _Field
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitFieldInfo(Me)
End Function
Public Function Update(field As FieldSymbol, type As TypeSymbol) As BoundFieldInfo
If field IsNot Me.Field OrElse type IsNot Me.Type Then
Dim result = New BoundFieldInfo(Me.Syntax, field, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMethodInfo
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MethodInfo, syntax, type, hasErrors)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol)
MyBase.New(BoundKind.MethodInfo, syntax, type)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMethodInfo(Me)
End Function
Public Function Update(method As MethodSymbol, type As TypeSymbol) As BoundMethodInfo
If method IsNot Me.Method OrElse type IsNot Me.Type Then
Dim result = New BoundMethodInfo(Me.Syntax, method, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TypeExpression, syntax, type, hasErrors OrElse unevaluatedReceiverOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnevaluatedReceiverOpt = unevaluatedReceiverOpt
Me._AliasOpt = aliasOpt
End Sub
Private ReadOnly _UnevaluatedReceiverOpt As BoundExpression
Public ReadOnly Property UnevaluatedReceiverOpt As BoundExpression
Get
Return _UnevaluatedReceiverOpt
End Get
End Property
Private ReadOnly _AliasOpt As AliasSymbol
Public ReadOnly Property AliasOpt As AliasSymbol
Get
Return _AliasOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeExpression(Me)
End Function
Public Function Update(unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, type As TypeSymbol) As BoundTypeExpression
If unevaluatedReceiverOpt IsNot Me.UnevaluatedReceiverOpt OrElse aliasOpt IsNot Me.AliasOpt OrElse type IsNot Me.Type Then
Dim result = New BoundTypeExpression(Me.Syntax, unevaluatedReceiverOpt, aliasOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeOrValueExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, data As BoundTypeOrValueData, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.TypeOrValueExpression, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Data = data
End Sub
Public Sub New(syntax As SyntaxNode, data As BoundTypeOrValueData, type As TypeSymbol)
MyBase.New(BoundKind.TypeOrValueExpression, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Data = data
End Sub
Private ReadOnly _Data As BoundTypeOrValueData
Public ReadOnly Property Data As BoundTypeOrValueData
Get
Return _Data
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeOrValueExpression(Me)
End Function
Public Function Update(data As BoundTypeOrValueData, type As TypeSymbol) As BoundTypeOrValueExpression
If data <> Me.Data OrElse type IsNot Me.Type Then
Dim result = New BoundTypeOrValueExpression(Me.Syntax, data, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNamespaceExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, namespaceSymbol As NamespaceSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NamespaceExpression, syntax, Nothing, hasErrors OrElse unevaluatedReceiverOpt.NonNullAndHasErrors())
Debug.Assert(namespaceSymbol IsNot Nothing, "Field 'namespaceSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnevaluatedReceiverOpt = unevaluatedReceiverOpt
Me._AliasOpt = aliasOpt
Me._NamespaceSymbol = namespaceSymbol
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _UnevaluatedReceiverOpt As BoundExpression
Public ReadOnly Property UnevaluatedReceiverOpt As BoundExpression
Get
Return _UnevaluatedReceiverOpt
End Get
End Property
Private ReadOnly _AliasOpt As AliasSymbol
Public ReadOnly Property AliasOpt As AliasSymbol
Get
Return _AliasOpt
End Get
End Property
Private ReadOnly _NamespaceSymbol As NamespaceSymbol
Public ReadOnly Property NamespaceSymbol As NamespaceSymbol
Get
Return _NamespaceSymbol
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNamespaceExpression(Me)
End Function
Public Function Update(unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, namespaceSymbol As NamespaceSymbol) As BoundNamespaceExpression
If unevaluatedReceiverOpt IsNot Me.UnevaluatedReceiverOpt OrElse aliasOpt IsNot Me.AliasOpt OrElse namespaceSymbol IsNot Me.NamespaceSymbol Then
Dim result = New BoundNamespaceExpression(Me.Syntax, unevaluatedReceiverOpt, aliasOpt, namespaceSymbol, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMethodDefIndex
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MethodDefIndex, syntax, type, hasErrors)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol)
MyBase.New(BoundKind.MethodDefIndex, syntax, type)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMethodDefIndex(Me)
End Function
Public Function Update(method As MethodSymbol, type As TypeSymbol) As BoundMethodDefIndex
If method IsNot Me.Method OrElse type IsNot Me.Type Then
Dim result = New BoundMethodDefIndex(Me.Syntax, method, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMaximumMethodDefIndex
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MaximumMethodDefIndex, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MaximumMethodDefIndex, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMaximumMethodDefIndex(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMaximumMethodDefIndex
If type IsNot Me.Type Then
Dim result = New BoundMaximumMethodDefIndex(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundInstrumentationPayloadRoot
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, analysisKind As Integer, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.InstrumentationPayloadRoot, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._AnalysisKind = analysisKind
Me._IsLValue = isLValue
End Sub
Public Sub New(syntax As SyntaxNode, analysisKind As Integer, isLValue As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.InstrumentationPayloadRoot, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._AnalysisKind = analysisKind
Me._IsLValue = isLValue
End Sub
Private ReadOnly _AnalysisKind As Integer
Public ReadOnly Property AnalysisKind As Integer
Get
Return _AnalysisKind
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInstrumentationPayloadRoot(Me)
End Function
Public Function Update(analysisKind As Integer, isLValue As Boolean, type As TypeSymbol) As BoundInstrumentationPayloadRoot
If analysisKind <> Me.AnalysisKind OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundInstrumentationPayloadRoot(Me.Syntax, analysisKind, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundModuleVersionId
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ModuleVersionId, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsLValue = isLValue
End Sub
Public Sub New(syntax As SyntaxNode, isLValue As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.ModuleVersionId, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsLValue = isLValue
End Sub
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitModuleVersionId(Me)
End Function
Public Function Update(isLValue As Boolean, type As TypeSymbol) As BoundModuleVersionId
If isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundModuleVersionId(Me.Syntax, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundModuleVersionIdString
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ModuleVersionIdString, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.ModuleVersionIdString, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitModuleVersionIdString(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundModuleVersionIdString
If type IsNot Me.Type Then
Dim result = New BoundModuleVersionIdString(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSourceDocumentIndex
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, document As Cci.DebugSourceDocument, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.SourceDocumentIndex, syntax, type, hasErrors)
Debug.Assert(document IsNot Nothing, "Field 'document' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Document = document
End Sub
Public Sub New(syntax As SyntaxNode, document As Cci.DebugSourceDocument, type As TypeSymbol)
MyBase.New(BoundKind.SourceDocumentIndex, syntax, type)
Debug.Assert(document IsNot Nothing, "Field 'document' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Document = document
End Sub
Private ReadOnly _Document As Cci.DebugSourceDocument
Public ReadOnly Property Document As Cci.DebugSourceDocument
Get
Return _Document
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSourceDocumentIndex(Me)
End Function
Public Function Update(document As Cci.DebugSourceDocument, type As TypeSymbol) As BoundSourceDocumentIndex
If document IsNot Me.Document OrElse type IsNot Me.Type Then
Dim result = New BoundSourceDocumentIndex(Me.Syntax, document, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As UnaryOperatorKind, operand As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnaryOperator, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._Operand = operand
Me._Checked = checked
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As UnaryOperatorKind
Public ReadOnly Property OperatorKind As UnaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnaryOperator(Me)
End Function
Public Function Update(operatorKind As UnaryOperatorKind, operand As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundUnaryOperator
If operatorKind <> Me.OperatorKind OrElse operand IsNot Me.Operand OrElse checked <> Me.Checked OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundUnaryOperator(Me.Syntax, operatorKind, operand, checked, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedUnaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As UnaryOperatorKind, underlyingExpression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedUnaryOperator, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._UnderlyingExpression = underlyingExpression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As UnaryOperatorKind
Public ReadOnly Property OperatorKind As UnaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedUnaryOperator(Me)
End Function
Public Function Update(operatorKind As UnaryOperatorKind, underlyingExpression As BoundExpression, type As TypeSymbol) As BoundUserDefinedUnaryOperator
If operatorKind <> Me.OperatorKind OrElse underlyingExpression IsNot Me.UnderlyingExpression OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedUnaryOperator(Me.Syntax, operatorKind, underlyingExpression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNullableIsTrueOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NullableIsTrueOperator, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNullableIsTrueOperator(Me)
End Function
Public Function Update(operand As BoundExpression, type As TypeSymbol) As BoundNullableIsTrueOperator
If operand IsNot Me.Operand OrElse type IsNot Me.Type Then
Dim result = New BoundNullableIsTrueOperator(Me.Syntax, operand, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBinaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BinaryOperator, syntax, type, hasErrors OrElse left.NonNullAndHasErrors() OrElse right.NonNullAndHasErrors())
Debug.Assert(left IsNot Nothing, "Field 'left' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(right IsNot Nothing, "Field 'right' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._Left = left
Me._Right = right
Me._Checked = checked
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As BinaryOperatorKind
Public ReadOnly Property OperatorKind As BinaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _Left As BoundExpression
Public ReadOnly Property Left As BoundExpression
Get
Return _Left
End Get
End Property
Private ReadOnly _Right As BoundExpression
Public ReadOnly Property Right As BoundExpression
Get
Return _Right
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBinaryOperator(Me)
End Function
Public Function Update(operatorKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundBinaryOperator
If operatorKind <> Me.OperatorKind OrElse left IsNot Me.Left OrElse right IsNot Me.Right OrElse checked <> Me.Checked OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundBinaryOperator(Me.Syntax, operatorKind, left, right, checked, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedBinaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As BinaryOperatorKind, underlyingExpression As BoundExpression, checked As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedBinaryOperator, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._UnderlyingExpression = underlyingExpression
Me._Checked = checked
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As BinaryOperatorKind
Public ReadOnly Property OperatorKind As BinaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedBinaryOperator(Me)
End Function
Public Function Update(operatorKind As BinaryOperatorKind, underlyingExpression As BoundExpression, checked As Boolean, type As TypeSymbol) As BoundUserDefinedBinaryOperator
If operatorKind <> Me.OperatorKind OrElse underlyingExpression IsNot Me.UnderlyingExpression OrElse checked <> Me.Checked OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedBinaryOperator(Me.Syntax, operatorKind, underlyingExpression, checked, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedShortCircuitingOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, leftOperand As BoundExpression, leftOperandPlaceholder As BoundRValuePlaceholder, leftTest As BoundExpression, bitwiseOperator As BoundUserDefinedBinaryOperator, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedShortCircuitingOperator, syntax, type, hasErrors OrElse leftOperand.NonNullAndHasErrors() OrElse leftOperandPlaceholder.NonNullAndHasErrors() OrElse leftTest.NonNullAndHasErrors() OrElse bitwiseOperator.NonNullAndHasErrors())
Debug.Assert(bitwiseOperator IsNot Nothing, "Field 'bitwiseOperator' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LeftOperand = leftOperand
Me._LeftOperandPlaceholder = leftOperandPlaceholder
Me._LeftTest = leftTest
Me._BitwiseOperator = bitwiseOperator
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LeftOperand As BoundExpression
Public ReadOnly Property LeftOperand As BoundExpression
Get
Return _LeftOperand
End Get
End Property
Private ReadOnly _LeftOperandPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property LeftOperandPlaceholder As BoundRValuePlaceholder
Get
Return _LeftOperandPlaceholder
End Get
End Property
Private ReadOnly _LeftTest As BoundExpression
Public ReadOnly Property LeftTest As BoundExpression
Get
Return _LeftTest
End Get
End Property
Private ReadOnly _BitwiseOperator As BoundUserDefinedBinaryOperator
Public ReadOnly Property BitwiseOperator As BoundUserDefinedBinaryOperator
Get
Return _BitwiseOperator
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedShortCircuitingOperator(Me)
End Function
Public Function Update(leftOperand As BoundExpression, leftOperandPlaceholder As BoundRValuePlaceholder, leftTest As BoundExpression, bitwiseOperator As BoundUserDefinedBinaryOperator, type As TypeSymbol) As BoundUserDefinedShortCircuitingOperator
If leftOperand IsNot Me.LeftOperand OrElse leftOperandPlaceholder IsNot Me.LeftOperandPlaceholder OrElse leftTest IsNot Me.LeftTest OrElse bitwiseOperator IsNot Me.BitwiseOperator OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedShortCircuitingOperator(Me.Syntax, leftOperand, leftOperandPlaceholder, leftTest, bitwiseOperator, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCompoundAssignmentTargetPlaceholder
Inherits BoundValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.CompoundAssignmentTargetPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.CompoundAssignmentTargetPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCompoundAssignmentTargetPlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundCompoundAssignmentTargetPlaceholder
If type IsNot Me.Type Then
Dim result = New BoundCompoundAssignmentTargetPlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAssignmentOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, left As BoundExpression, leftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder, right As BoundExpression, suppressObjectClone As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AssignmentOperator, syntax, type, hasErrors OrElse left.NonNullAndHasErrors() OrElse leftOnTheRightOpt.NonNullAndHasErrors() OrElse right.NonNullAndHasErrors())
Debug.Assert(left IsNot Nothing, "Field 'left' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(right IsNot Nothing, "Field 'right' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Left = left
Me._LeftOnTheRightOpt = leftOnTheRightOpt
Me._Right = right
Me._SuppressObjectClone = suppressObjectClone
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Left As BoundExpression
Public ReadOnly Property Left As BoundExpression
Get
Return _Left
End Get
End Property
Private ReadOnly _LeftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder
Public ReadOnly Property LeftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder
Get
Return _LeftOnTheRightOpt
End Get
End Property
Private ReadOnly _Right As BoundExpression
Public ReadOnly Property Right As BoundExpression
Get
Return _Right
End Get
End Property
Private ReadOnly _SuppressObjectClone As Boolean
Public ReadOnly Property SuppressObjectClone As Boolean
Get
Return _SuppressObjectClone
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAssignmentOperator(Me)
End Function
Public Function Update(left As BoundExpression, leftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder, right As BoundExpression, suppressObjectClone As Boolean, type As TypeSymbol) As BoundAssignmentOperator
If left IsNot Me.Left OrElse leftOnTheRightOpt IsNot Me.LeftOnTheRightOpt OrElse right IsNot Me.Right OrElse suppressObjectClone <> Me.SuppressObjectClone OrElse type IsNot Me.Type Then
Dim result = New BoundAssignmentOperator(Me.Syntax, left, leftOnTheRightOpt, right, suppressObjectClone, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundReferenceAssignment
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, byRefLocal As BoundLocal, lValue As BoundExpression, isLValue As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ReferenceAssignment, syntax, type, hasErrors OrElse byRefLocal.NonNullAndHasErrors() OrElse lValue.NonNullAndHasErrors())
Debug.Assert(byRefLocal IsNot Nothing, "Field 'byRefLocal' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ByRefLocal = byRefLocal
Me._LValue = lValue
Me._IsLValue = isLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ByRefLocal As BoundLocal
Public ReadOnly Property ByRefLocal As BoundLocal
Get
Return _ByRefLocal
End Get
End Property
Private ReadOnly _LValue As BoundExpression
Public ReadOnly Property LValue As BoundExpression
Get
Return _LValue
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitReferenceAssignment(Me)
End Function
Public Function Update(byRefLocal As BoundLocal, lValue As BoundExpression, isLValue As Boolean, type As TypeSymbol) As BoundReferenceAssignment
If byRefLocal IsNot Me.ByRefLocal OrElse lValue IsNot Me.LValue OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundReferenceAssignment(Me.Syntax, byRefLocal, lValue, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAddressOfOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, withDependencies As Boolean, methodGroup As BoundMethodGroup, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AddressOfOperator, syntax, Nothing, hasErrors OrElse methodGroup.NonNullAndHasErrors())
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(methodGroup IsNot Nothing, "Field 'methodGroup' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._WithDependencies = withDependencies
Me._MethodGroup = methodGroup
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _WithDependencies As Boolean
Public ReadOnly Property WithDependencies As Boolean
Get
Return _WithDependencies
End Get
End Property
Private ReadOnly _MethodGroup As BoundMethodGroup
Public ReadOnly Property MethodGroup As BoundMethodGroup
Get
Return _MethodGroup
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAddressOfOperator(Me)
End Function
Public Function Update(binder As Binder, withDependencies As Boolean, methodGroup As BoundMethodGroup) As BoundAddressOfOperator
If binder IsNot Me.Binder OrElse withDependencies <> Me.WithDependencies OrElse methodGroup IsNot Me.MethodGroup Then
Dim result = New BoundAddressOfOperator(Me.Syntax, binder, withDependencies, methodGroup, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTernaryConditionalExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, whenTrue As BoundExpression, whenFalse As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TernaryConditionalExpression, syntax, type, hasErrors OrElse condition.NonNullAndHasErrors() OrElse whenTrue.NonNullAndHasErrors() OrElse whenFalse.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(whenTrue IsNot Nothing, "Field 'whenTrue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(whenFalse IsNot Nothing, "Field 'whenFalse' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._WhenTrue = whenTrue
Me._WhenFalse = whenFalse
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _WhenTrue As BoundExpression
Public ReadOnly Property WhenTrue As BoundExpression
Get
Return _WhenTrue
End Get
End Property
Private ReadOnly _WhenFalse As BoundExpression
Public ReadOnly Property WhenFalse As BoundExpression
Get
Return _WhenFalse
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTernaryConditionalExpression(Me)
End Function
Public Function Update(condition As BoundExpression, whenTrue As BoundExpression, whenFalse As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundTernaryConditionalExpression
If condition IsNot Me.Condition OrElse whenTrue IsNot Me.WhenTrue OrElse whenFalse IsNot Me.WhenFalse OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundTernaryConditionalExpression(Me.Syntax, condition, whenTrue, whenFalse, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBinaryConditionalExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, testExpression As BoundExpression, convertedTestExpression As BoundExpression, testExpressionPlaceholder As BoundRValuePlaceholder, elseExpression As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BinaryConditionalExpression, syntax, type, hasErrors OrElse testExpression.NonNullAndHasErrors() OrElse convertedTestExpression.NonNullAndHasErrors() OrElse testExpressionPlaceholder.NonNullAndHasErrors() OrElse elseExpression.NonNullAndHasErrors())
Debug.Assert(testExpression IsNot Nothing, "Field 'testExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(elseExpression IsNot Nothing, "Field 'elseExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TestExpression = testExpression
Me._ConvertedTestExpression = convertedTestExpression
Me._TestExpressionPlaceholder = testExpressionPlaceholder
Me._ElseExpression = elseExpression
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _TestExpression As BoundExpression
Public ReadOnly Property TestExpression As BoundExpression
Get
Return _TestExpression
End Get
End Property
Private ReadOnly _ConvertedTestExpression As BoundExpression
Public ReadOnly Property ConvertedTestExpression As BoundExpression
Get
Return _ConvertedTestExpression
End Get
End Property
Private ReadOnly _TestExpressionPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property TestExpressionPlaceholder As BoundRValuePlaceholder
Get
Return _TestExpressionPlaceholder
End Get
End Property
Private ReadOnly _ElseExpression As BoundExpression
Public ReadOnly Property ElseExpression As BoundExpression
Get
Return _ElseExpression
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBinaryConditionalExpression(Me)
End Function
Public Function Update(testExpression As BoundExpression, convertedTestExpression As BoundExpression, testExpressionPlaceholder As BoundRValuePlaceholder, elseExpression As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundBinaryConditionalExpression
If testExpression IsNot Me.TestExpression OrElse convertedTestExpression IsNot Me.ConvertedTestExpression OrElse testExpressionPlaceholder IsNot Me.TestExpressionPlaceholder OrElse elseExpression IsNot Me.ElseExpression OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundBinaryConditionalExpression(Me.Syntax, testExpression, convertedTestExpression, testExpressionPlaceholder, elseExpression, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundConversionOrCast
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundConversion
Inherits BoundConversionOrCast
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, checked As Boolean, explicitCastInCode As Boolean, constantValueOpt As ConstantValue, extendedInfoOpt As BoundExtendedConversionInfo, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Conversion, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse extendedInfoOpt.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._ConversionKind = conversionKind
Me._Checked = checked
Me._ExplicitCastInCode = explicitCastInCode
Me._ConstantValueOpt = constantValueOpt
Me._ExtendedInfoOpt = extendedInfoOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public Overrides ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _ConversionKind As ConversionKind
Public Overrides ReadOnly Property ConversionKind As ConversionKind
Get
Return _ConversionKind
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _ExplicitCastInCode As Boolean
Public Overrides ReadOnly Property ExplicitCastInCode As Boolean
Get
Return _ExplicitCastInCode
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _ExtendedInfoOpt As BoundExtendedConversionInfo
Public ReadOnly Property ExtendedInfoOpt As BoundExtendedConversionInfo
Get
Return _ExtendedInfoOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConversion(Me)
End Function
Public Function Update(operand As BoundExpression, conversionKind As ConversionKind, checked As Boolean, explicitCastInCode As Boolean, constantValueOpt As ConstantValue, extendedInfoOpt As BoundExtendedConversionInfo, type As TypeSymbol) As BoundConversion
If operand IsNot Me.Operand OrElse conversionKind <> Me.ConversionKind OrElse checked <> Me.Checked OrElse explicitCastInCode <> Me.ExplicitCastInCode OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse extendedInfoOpt IsNot Me.ExtendedInfoOpt OrElse type IsNot Me.Type Then
Dim result = New BoundConversion(Me.Syntax, operand, conversionKind, checked, explicitCastInCode, constantValueOpt, extendedInfoOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundExtendedConversionInfo
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend NotInheritable Class BoundRelaxationLambda
Inherits BoundExtendedConversionInfo
Public Sub New(syntax As SyntaxNode, lambda As BoundLambda, receiverPlaceholderOpt As BoundRValuePlaceholder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RelaxationLambda, syntax, hasErrors OrElse lambda.NonNullAndHasErrors() OrElse receiverPlaceholderOpt.NonNullAndHasErrors())
Debug.Assert(lambda IsNot Nothing, "Field 'lambda' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Lambda = lambda
Me._ReceiverPlaceholderOpt = receiverPlaceholderOpt
End Sub
Private ReadOnly _Lambda As BoundLambda
Public ReadOnly Property Lambda As BoundLambda
Get
Return _Lambda
End Get
End Property
Private ReadOnly _ReceiverPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property ReceiverPlaceholderOpt As BoundRValuePlaceholder
Get
Return _ReceiverPlaceholderOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRelaxationLambda(Me)
End Function
Public Function Update(lambda As BoundLambda, receiverPlaceholderOpt As BoundRValuePlaceholder) As BoundRelaxationLambda
If lambda IsNot Me.Lambda OrElse receiverPlaceholderOpt IsNot Me.ReceiverPlaceholderOpt Then
Dim result = New BoundRelaxationLambda(Me.Syntax, lambda, receiverPlaceholderOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConvertedTupleElements
Inherits BoundExtendedConversionInfo
Public Sub New(syntax As SyntaxNode, elementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder), convertedElements As ImmutableArray(Of BoundExpression), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConvertedTupleElements, syntax, hasErrors OrElse elementPlaceholders.NonNullAndHasErrors() OrElse convertedElements.NonNullAndHasErrors())
Debug.Assert(Not (elementPlaceholders.IsDefault), "Field 'elementPlaceholders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (convertedElements.IsDefault), "Field 'convertedElements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ElementPlaceholders = elementPlaceholders
Me._ConvertedElements = convertedElements
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ElementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder)
Public ReadOnly Property ElementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder)
Get
Return _ElementPlaceholders
End Get
End Property
Private ReadOnly _ConvertedElements As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ConvertedElements As ImmutableArray(Of BoundExpression)
Get
Return _ConvertedElements
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConvertedTupleElements(Me)
End Function
Public Function Update(elementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder), convertedElements As ImmutableArray(Of BoundExpression)) As BoundConvertedTupleElements
If elementPlaceholders <> Me.ElementPlaceholders OrElse convertedElements <> Me.ConvertedElements Then
Dim result = New BoundConvertedTupleElements(Me.Syntax, elementPlaceholders, convertedElements, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedConversion
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, underlyingExpression As BoundExpression, inOutConversionFlags As Byte, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedConversion, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingExpression = underlyingExpression
Me._InOutConversionFlags = inOutConversionFlags
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
Private ReadOnly _InOutConversionFlags As Byte
Public ReadOnly Property InOutConversionFlags As Byte
Get
Return _InOutConversionFlags
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedConversion(Me)
End Function
Public Function Update(underlyingExpression As BoundExpression, inOutConversionFlags As Byte, type As TypeSymbol) As BoundUserDefinedConversion
If underlyingExpression IsNot Me.UnderlyingExpression OrElse inOutConversionFlags <> Me.InOutConversionFlags OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedConversion(Me.Syntax, underlyingExpression, inOutConversionFlags, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDirectCast
Inherits BoundConversionOrCast
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, suppressVirtualCalls As Boolean, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DirectCast, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse relaxationLambdaOpt.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._ConversionKind = conversionKind
Me._SuppressVirtualCalls = suppressVirtualCalls
Me._ConstantValueOpt = constantValueOpt
Me._RelaxationLambdaOpt = relaxationLambdaOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public Overrides ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _ConversionKind As ConversionKind
Public Overrides ReadOnly Property ConversionKind As ConversionKind
Get
Return _ConversionKind
End Get
End Property
Private ReadOnly _SuppressVirtualCalls As Boolean
Public Overrides ReadOnly Property SuppressVirtualCalls As Boolean
Get
Return _SuppressVirtualCalls
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _RelaxationLambdaOpt As BoundLambda
Public ReadOnly Property RelaxationLambdaOpt As BoundLambda
Get
Return _RelaxationLambdaOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDirectCast(Me)
End Function
Public Function Update(operand As BoundExpression, conversionKind As ConversionKind, suppressVirtualCalls As Boolean, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol) As BoundDirectCast
If operand IsNot Me.Operand OrElse conversionKind <> Me.ConversionKind OrElse suppressVirtualCalls <> Me.SuppressVirtualCalls OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse relaxationLambdaOpt IsNot Me.RelaxationLambdaOpt OrElse type IsNot Me.Type Then
Dim result = New BoundDirectCast(Me.Syntax, operand, conversionKind, suppressVirtualCalls, constantValueOpt, relaxationLambdaOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTryCast
Inherits BoundConversionOrCast
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TryCast, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse relaxationLambdaOpt.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._ConversionKind = conversionKind
Me._ConstantValueOpt = constantValueOpt
Me._RelaxationLambdaOpt = relaxationLambdaOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public Overrides ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _ConversionKind As ConversionKind
Public Overrides ReadOnly Property ConversionKind As ConversionKind
Get
Return _ConversionKind
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _RelaxationLambdaOpt As BoundLambda
Public ReadOnly Property RelaxationLambdaOpt As BoundLambda
Get
Return _RelaxationLambdaOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTryCast(Me)
End Function
Public Function Update(operand As BoundExpression, conversionKind As ConversionKind, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol) As BoundTryCast
If operand IsNot Me.Operand OrElse conversionKind <> Me.ConversionKind OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse relaxationLambdaOpt IsNot Me.RelaxationLambdaOpt OrElse type IsNot Me.Type Then
Dim result = New BoundTryCast(Me.Syntax, operand, conversionKind, constantValueOpt, relaxationLambdaOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeOf
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, isTypeOfIsNotExpression As Boolean, targetType As TypeSymbol, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TypeOf, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(targetType IsNot Nothing, "Field 'targetType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._IsTypeOfIsNotExpression = isTypeOfIsNotExpression
Me._TargetType = targetType
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _IsTypeOfIsNotExpression As Boolean
Public ReadOnly Property IsTypeOfIsNotExpression As Boolean
Get
Return _IsTypeOfIsNotExpression
End Get
End Property
Private ReadOnly _TargetType As TypeSymbol
Public ReadOnly Property TargetType As TypeSymbol
Get
Return _TargetType
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeOf(Me)
End Function
Public Function Update(operand As BoundExpression, isTypeOfIsNotExpression As Boolean, targetType As TypeSymbol, type As TypeSymbol) As BoundTypeOf
If operand IsNot Me.Operand OrElse isTypeOfIsNotExpression <> Me.IsTypeOfIsNotExpression OrElse targetType IsNot Me.TargetType OrElse type IsNot Me.Type Then
Dim result = New BoundTypeOf(Me.Syntax, operand, isTypeOfIsNotExpression, targetType, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundStatement
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend NotInheritable Class BoundSequencePoint
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statementOpt As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SequencePoint, syntax, hasErrors OrElse statementOpt.NonNullAndHasErrors())
Me._StatementOpt = statementOpt
End Sub
Private ReadOnly _StatementOpt As BoundStatement
Public ReadOnly Property StatementOpt As BoundStatement
Get
Return _StatementOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequencePoint(Me)
End Function
Public Function Update(statementOpt As BoundStatement) As BoundSequencePoint
If statementOpt IsNot Me.StatementOpt Then
Dim result = New BoundSequencePoint(Me.Syntax, statementOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSequencePointExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SequencePointExpression, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequencePointExpression(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundSequencePointExpression
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundSequencePointExpression(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSequencePointWithSpan
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statementOpt As BoundStatement, span As TextSpan, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SequencePointWithSpan, syntax, hasErrors OrElse statementOpt.NonNullAndHasErrors())
Me._StatementOpt = statementOpt
Me._Span = span
End Sub
Private ReadOnly _StatementOpt As BoundStatement
Public ReadOnly Property StatementOpt As BoundStatement
Get
Return _StatementOpt
End Get
End Property
Private ReadOnly _Span As TextSpan
Public ReadOnly Property Span As TextSpan
Get
Return _Span
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequencePointWithSpan(Me)
End Function
Public Function Update(statementOpt As BoundStatement, span As TextSpan) As BoundSequencePointWithSpan
If statementOpt IsNot Me.StatementOpt OrElse span <> Me.Span Then
Dim result = New BoundSequencePointWithSpan(Me.Syntax, statementOpt, span, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNoOpStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, flavor As NoOpStatementFlavor, hasErrors As Boolean)
MyBase.New(BoundKind.NoOpStatement, syntax, hasErrors)
Me._Flavor = flavor
End Sub
Public Sub New(syntax As SyntaxNode, flavor As NoOpStatementFlavor)
MyBase.New(BoundKind.NoOpStatement, syntax)
Me._Flavor = flavor
End Sub
Private ReadOnly _Flavor As NoOpStatementFlavor
Public ReadOnly Property Flavor As NoOpStatementFlavor
Get
Return _Flavor
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNoOpStatement(Me)
End Function
Public Function Update(flavor As NoOpStatementFlavor) As BoundNoOpStatement
If flavor <> Me.Flavor Then
Dim result = New BoundNoOpStatement(Me.Syntax, flavor, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundMethodOrPropertyGroup
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, Nothing, hasErrors)
Me._ReceiverOpt = receiverOpt
Me._QualificationKind = qualificationKind
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _QualificationKind As QualificationKind
Public ReadOnly Property QualificationKind As QualificationKind
Get
Return _QualificationKind
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundMethodGroup
Inherits BoundMethodOrPropertyGroup
Public Sub New(syntax As SyntaxNode, typeArgumentsOpt As BoundTypeArguments, methods As ImmutableArray(Of MethodSymbol), pendingExtensionMethodsOpt As ExtensionMethodGroup, resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.MethodGroup, syntax, receiverOpt, qualificationKind, hasErrors OrElse typeArgumentsOpt.NonNullAndHasErrors() OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(Not (methods.IsDefault), "Field 'methods' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TypeArgumentsOpt = typeArgumentsOpt
Me._Methods = methods
Me._PendingExtensionMethodsOpt = pendingExtensionMethodsOpt
Me._ResultKind = resultKind
End Sub
Private ReadOnly _TypeArgumentsOpt As BoundTypeArguments
Public ReadOnly Property TypeArgumentsOpt As BoundTypeArguments
Get
Return _TypeArgumentsOpt
End Get
End Property
Private ReadOnly _Methods As ImmutableArray(Of MethodSymbol)
Public ReadOnly Property Methods As ImmutableArray(Of MethodSymbol)
Get
Return _Methods
End Get
End Property
Private ReadOnly _PendingExtensionMethodsOpt As ExtensionMethodGroup
Public ReadOnly Property PendingExtensionMethodsOpt As ExtensionMethodGroup
Get
Return _PendingExtensionMethodsOpt
End Get
End Property
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMethodGroup(Me)
End Function
Public Function Update(typeArgumentsOpt As BoundTypeArguments, methods As ImmutableArray(Of MethodSymbol), pendingExtensionMethodsOpt As ExtensionMethodGroup, resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind) As BoundMethodGroup
If typeArgumentsOpt IsNot Me.TypeArgumentsOpt OrElse methods <> Me.Methods OrElse pendingExtensionMethodsOpt IsNot Me.PendingExtensionMethodsOpt OrElse resultKind <> Me.ResultKind OrElse receiverOpt IsNot Me.ReceiverOpt OrElse qualificationKind <> Me.QualificationKind Then
Dim result = New BoundMethodGroup(Me.Syntax, typeArgumentsOpt, methods, pendingExtensionMethodsOpt, resultKind, receiverOpt, qualificationKind, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPropertyGroup
Inherits BoundMethodOrPropertyGroup
Public Sub New(syntax As SyntaxNode, properties As ImmutableArray(Of PropertySymbol), resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.PropertyGroup, syntax, receiverOpt, qualificationKind, hasErrors OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(Not (properties.IsDefault), "Field 'properties' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Properties = properties
Me._ResultKind = resultKind
End Sub
Private ReadOnly _Properties As ImmutableArray(Of PropertySymbol)
Public ReadOnly Property Properties As ImmutableArray(Of PropertySymbol)
Get
Return _Properties
End Get
End Property
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPropertyGroup(Me)
End Function
Public Function Update(properties As ImmutableArray(Of PropertySymbol), resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind) As BoundPropertyGroup
If properties <> Me.Properties OrElse resultKind <> Me.ResultKind OrElse receiverOpt IsNot Me.ReceiverOpt OrElse qualificationKind <> Me.QualificationKind Then
Dim result = New BoundPropertyGroup(Me.Syntax, properties, resultKind, receiverOpt, qualificationKind, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundReturnStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expressionOpt As BoundExpression, functionLocalOpt As LocalSymbol, exitLabelOpt As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ReturnStatement, syntax, hasErrors OrElse expressionOpt.NonNullAndHasErrors())
Me._ExpressionOpt = expressionOpt
Me._FunctionLocalOpt = functionLocalOpt
Me._ExitLabelOpt = exitLabelOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ExpressionOpt As BoundExpression
Public ReadOnly Property ExpressionOpt As BoundExpression
Get
Return _ExpressionOpt
End Get
End Property
Private ReadOnly _FunctionLocalOpt As LocalSymbol
Public ReadOnly Property FunctionLocalOpt As LocalSymbol
Get
Return _FunctionLocalOpt
End Get
End Property
Private ReadOnly _ExitLabelOpt As LabelSymbol
Public ReadOnly Property ExitLabelOpt As LabelSymbol
Get
Return _ExitLabelOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitReturnStatement(Me)
End Function
Public Function Update(expressionOpt As BoundExpression, functionLocalOpt As LocalSymbol, exitLabelOpt As LabelSymbol) As BoundReturnStatement
If expressionOpt IsNot Me.ExpressionOpt OrElse functionLocalOpt IsNot Me.FunctionLocalOpt OrElse exitLabelOpt IsNot Me.ExitLabelOpt Then
Dim result = New BoundReturnStatement(Me.Syntax, expressionOpt, functionLocalOpt, exitLabelOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundYieldStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.YieldStatement, syntax, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitYieldStatement(Me)
End Function
Public Function Update(expression As BoundExpression) As BoundYieldStatement
If expression IsNot Me.Expression Then
Dim result = New BoundYieldStatement(Me.Syntax, expression, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundThrowStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expressionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ThrowStatement, syntax, hasErrors OrElse expressionOpt.NonNullAndHasErrors())
Me._ExpressionOpt = expressionOpt
End Sub
Private ReadOnly _ExpressionOpt As BoundExpression
Public ReadOnly Property ExpressionOpt As BoundExpression
Get
Return _ExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitThrowStatement(Me)
End Function
Public Function Update(expressionOpt As BoundExpression) As BoundThrowStatement
If expressionOpt IsNot Me.ExpressionOpt Then
Dim result = New BoundThrowStatement(Me.Syntax, expressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRedimStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, clauses As ImmutableArray(Of BoundRedimClause), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RedimStatement, syntax, hasErrors OrElse clauses.NonNullAndHasErrors())
Debug.Assert(Not (clauses.IsDefault), "Field 'clauses' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Clauses = clauses
End Sub
Private ReadOnly _Clauses As ImmutableArray(Of BoundRedimClause)
Public ReadOnly Property Clauses As ImmutableArray(Of BoundRedimClause)
Get
Return _Clauses
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRedimStatement(Me)
End Function
Public Function Update(clauses As ImmutableArray(Of BoundRedimClause)) As BoundRedimStatement
If clauses <> Me.Clauses Then
Dim result = New BoundRedimStatement(Me.Syntax, clauses, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRedimClause
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, indices As ImmutableArray(Of BoundExpression), arrayTypeOpt As ArrayTypeSymbol, preserve As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RedimClause, syntax, hasErrors OrElse operand.NonNullAndHasErrors() OrElse indices.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (indices.IsDefault), "Field 'indices' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._Indices = indices
Me._ArrayTypeOpt = arrayTypeOpt
Me._Preserve = preserve
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _Indices As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Indices As ImmutableArray(Of BoundExpression)
Get
Return _Indices
End Get
End Property
Private ReadOnly _ArrayTypeOpt As ArrayTypeSymbol
Public ReadOnly Property ArrayTypeOpt As ArrayTypeSymbol
Get
Return _ArrayTypeOpt
End Get
End Property
Private ReadOnly _Preserve As Boolean
Public ReadOnly Property Preserve As Boolean
Get
Return _Preserve
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRedimClause(Me)
End Function
Public Function Update(operand As BoundExpression, indices As ImmutableArray(Of BoundExpression), arrayTypeOpt As ArrayTypeSymbol, preserve As Boolean) As BoundRedimClause
If operand IsNot Me.Operand OrElse indices <> Me.Indices OrElse arrayTypeOpt IsNot Me.ArrayTypeOpt OrElse preserve <> Me.Preserve Then
Dim result = New BoundRedimClause(Me.Syntax, operand, indices, arrayTypeOpt, preserve, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundEraseStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, clauses As ImmutableArray(Of BoundAssignmentOperator), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.EraseStatement, syntax, hasErrors OrElse clauses.NonNullAndHasErrors())
Debug.Assert(Not (clauses.IsDefault), "Field 'clauses' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Clauses = clauses
End Sub
Private ReadOnly _Clauses As ImmutableArray(Of BoundAssignmentOperator)
Public ReadOnly Property Clauses As ImmutableArray(Of BoundAssignmentOperator)
Get
Return _Clauses
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitEraseStatement(Me)
End Function
Public Function Update(clauses As ImmutableArray(Of BoundAssignmentOperator)) As BoundEraseStatement
If clauses <> Me.Clauses Then
Dim result = New BoundEraseStatement(Me.Syntax, clauses, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCall
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, methodGroupOpt As BoundMethodGroup, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, constantValueOpt As ConstantValue, isLValue As Boolean, suppressObjectClone As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Call, syntax, type, hasErrors OrElse methodGroupOpt.NonNullAndHasErrors() OrElse receiverOpt.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors())
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
Me._MethodGroupOpt = methodGroupOpt
Me._ReceiverOpt = receiverOpt
Me._Arguments = arguments
Me._DefaultArguments = defaultArguments
Me._ConstantValueOpt = constantValueOpt
Me._IsLValue = isLValue
Me._SuppressObjectClone = suppressObjectClone
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
Private ReadOnly _MethodGroupOpt As BoundMethodGroup
Public ReadOnly Property MethodGroupOpt As BoundMethodGroup
Get
Return _MethodGroupOpt
End Get
End Property
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
Private ReadOnly _DefaultArguments As BitVector
Public ReadOnly Property DefaultArguments As BitVector
Get
Return _DefaultArguments
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _SuppressObjectClone As Boolean
Public ReadOnly Property SuppressObjectClone As Boolean
Get
Return _SuppressObjectClone
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCall(Me)
End Function
Public Function Update(method As MethodSymbol, methodGroupOpt As BoundMethodGroup, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, constantValueOpt As ConstantValue, isLValue As Boolean, suppressObjectClone As Boolean, type As TypeSymbol) As BoundCall
If method IsNot Me.Method OrElse methodGroupOpt IsNot Me.MethodGroupOpt OrElse receiverOpt IsNot Me.ReceiverOpt OrElse arguments <> Me.Arguments OrElse defaultArguments <> Me.DefaultArguments OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse isLValue <> Me.IsLValue OrElse suppressObjectClone <> Me.SuppressObjectClone OrElse type IsNot Me.Type Then
Dim result = New BoundCall(Me.Syntax, method, methodGroupOpt, receiverOpt, arguments, defaultArguments, constantValueOpt, isLValue, suppressObjectClone, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAttribute
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, constructor As MethodSymbol, constructorArguments As ImmutableArray(Of BoundExpression), namedArguments As ImmutableArray(Of BoundExpression), resultKind As LookupResultKind, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Attribute, syntax, type, hasErrors OrElse constructorArguments.NonNullAndHasErrors() OrElse namedArguments.NonNullAndHasErrors())
Debug.Assert(Not (constructorArguments.IsDefault), "Field 'constructorArguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (namedArguments.IsDefault), "Field 'namedArguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Constructor = constructor
Me._ConstructorArguments = constructorArguments
Me._NamedArguments = namedArguments
Me._ResultKind = resultKind
End Sub
Private ReadOnly _Constructor As MethodSymbol
Public ReadOnly Property Constructor As MethodSymbol
Get
Return _Constructor
End Get
End Property
Private ReadOnly _ConstructorArguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ConstructorArguments As ImmutableArray(Of BoundExpression)
Get
Return _ConstructorArguments
End Get
End Property
Private ReadOnly _NamedArguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property NamedArguments As ImmutableArray(Of BoundExpression)
Get
Return _NamedArguments
End Get
End Property
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAttribute(Me)
End Function
Public Function Update(constructor As MethodSymbol, constructorArguments As ImmutableArray(Of BoundExpression), namedArguments As ImmutableArray(Of BoundExpression), resultKind As LookupResultKind, type As TypeSymbol) As BoundAttribute
If constructor IsNot Me.Constructor OrElse constructorArguments <> Me.ConstructorArguments OrElse namedArguments <> Me.NamedArguments OrElse resultKind <> Me.ResultKind OrElse type IsNot Me.Type Then
Dim result = New BoundAttribute(Me.Syntax, constructor, constructorArguments, namedArguments, resultKind, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateMemberAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, nameOpt As String, containerTypeOpt As TypeSymbol, receiverOpt As BoundExpression, typeArgumentsOpt As BoundTypeArguments, accessKind As LateBoundAccessKind, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateMemberAccess, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors() OrElse typeArgumentsOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._NameOpt = nameOpt
Me._ContainerTypeOpt = containerTypeOpt
Me._ReceiverOpt = receiverOpt
Me._TypeArgumentsOpt = typeArgumentsOpt
Me._AccessKind = accessKind
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _NameOpt As String
Public ReadOnly Property NameOpt As String
Get
Return _NameOpt
End Get
End Property
Private ReadOnly _ContainerTypeOpt As TypeSymbol
Public ReadOnly Property ContainerTypeOpt As TypeSymbol
Get
Return _ContainerTypeOpt
End Get
End Property
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _TypeArgumentsOpt As BoundTypeArguments
Public ReadOnly Property TypeArgumentsOpt As BoundTypeArguments
Get
Return _TypeArgumentsOpt
End Get
End Property
Private ReadOnly _AccessKind As LateBoundAccessKind
Public ReadOnly Property AccessKind As LateBoundAccessKind
Get
Return _AccessKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateMemberAccess(Me)
End Function
Public Function Update(nameOpt As String, containerTypeOpt As TypeSymbol, receiverOpt As BoundExpression, typeArgumentsOpt As BoundTypeArguments, accessKind As LateBoundAccessKind, type As TypeSymbol) As BoundLateMemberAccess
If nameOpt IsNot Me.NameOpt OrElse containerTypeOpt IsNot Me.ContainerTypeOpt OrElse receiverOpt IsNot Me.ReceiverOpt OrElse typeArgumentsOpt IsNot Me.TypeArgumentsOpt OrElse accessKind <> Me.AccessKind OrElse type IsNot Me.Type Then
Dim result = New BoundLateMemberAccess(Me.Syntax, nameOpt, containerTypeOpt, receiverOpt, typeArgumentsOpt, accessKind, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateInvocation
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, member As BoundExpression, argumentsOpt As ImmutableArray(Of BoundExpression), argumentNamesOpt As ImmutableArray(Of string), accessKind As LateBoundAccessKind, methodOrPropertyGroupOpt As BoundMethodOrPropertyGroup, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateInvocation, syntax, type, hasErrors OrElse member.NonNullAndHasErrors() OrElse argumentsOpt.NonNullAndHasErrors() OrElse methodOrPropertyGroupOpt.NonNullAndHasErrors())
Debug.Assert(member IsNot Nothing, "Field 'member' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Member = member
Me._ArgumentsOpt = argumentsOpt
Me._ArgumentNamesOpt = argumentNamesOpt
Me._AccessKind = accessKind
Me._MethodOrPropertyGroupOpt = methodOrPropertyGroupOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Member As BoundExpression
Public ReadOnly Property Member As BoundExpression
Get
Return _Member
End Get
End Property
Private ReadOnly _ArgumentsOpt As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ArgumentsOpt As ImmutableArray(Of BoundExpression)
Get
Return _ArgumentsOpt
End Get
End Property
Private ReadOnly _ArgumentNamesOpt As ImmutableArray(Of string)
Public ReadOnly Property ArgumentNamesOpt As ImmutableArray(Of string)
Get
Return _ArgumentNamesOpt
End Get
End Property
Private ReadOnly _AccessKind As LateBoundAccessKind
Public ReadOnly Property AccessKind As LateBoundAccessKind
Get
Return _AccessKind
End Get
End Property
Private ReadOnly _MethodOrPropertyGroupOpt As BoundMethodOrPropertyGroup
Public ReadOnly Property MethodOrPropertyGroupOpt As BoundMethodOrPropertyGroup
Get
Return _MethodOrPropertyGroupOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateInvocation(Me)
End Function
Public Function Update(member As BoundExpression, argumentsOpt As ImmutableArray(Of BoundExpression), argumentNamesOpt As ImmutableArray(Of string), accessKind As LateBoundAccessKind, methodOrPropertyGroupOpt As BoundMethodOrPropertyGroup, type As TypeSymbol) As BoundLateInvocation
If member IsNot Me.Member OrElse argumentsOpt <> Me.ArgumentsOpt OrElse argumentNamesOpt <> Me.ArgumentNamesOpt OrElse accessKind <> Me.AccessKind OrElse methodOrPropertyGroupOpt IsNot Me.MethodOrPropertyGroupOpt OrElse type IsNot Me.Type Then
Dim result = New BoundLateInvocation(Me.Syntax, member, argumentsOpt, argumentNamesOpt, accessKind, methodOrPropertyGroupOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateAddressOfOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, memberAccess As BoundLateMemberAccess, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateAddressOfOperator, syntax, type, hasErrors OrElse memberAccess.NonNullAndHasErrors())
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(memberAccess IsNot Nothing, "Field 'memberAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._MemberAccess = memberAccess
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _MemberAccess As BoundLateMemberAccess
Public ReadOnly Property MemberAccess As BoundLateMemberAccess
Get
Return _MemberAccess
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateAddressOfOperator(Me)
End Function
Public Function Update(binder As Binder, memberAccess As BoundLateMemberAccess, type As TypeSymbol) As BoundLateAddressOfOperator
If binder IsNot Me.Binder OrElse memberAccess IsNot Me.MemberAccess OrElse type IsNot Me.Type Then
Dim result = New BoundLateAddressOfOperator(Me.Syntax, binder, memberAccess, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundTupleExpression
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Arguments = arguments
End Sub
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundTupleLiteral
Inherits BoundTupleExpression
Public Sub New(syntax As SyntaxNode, inferredType As TupleTypeSymbol, argumentNamesOpt As ImmutableArray(Of String), inferredNamesOpt As ImmutableArray(Of Boolean), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TupleLiteral, syntax, arguments, type, hasErrors OrElse arguments.NonNullAndHasErrors())
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InferredType = inferredType
Me._ArgumentNamesOpt = argumentNamesOpt
Me._InferredNamesOpt = inferredNamesOpt
End Sub
Private ReadOnly _InferredType As TupleTypeSymbol
Public ReadOnly Property InferredType As TupleTypeSymbol
Get
Return _InferredType
End Get
End Property
Private ReadOnly _ArgumentNamesOpt As ImmutableArray(Of String)
Public ReadOnly Property ArgumentNamesOpt As ImmutableArray(Of String)
Get
Return _ArgumentNamesOpt
End Get
End Property
Private ReadOnly _InferredNamesOpt As ImmutableArray(Of Boolean)
Public ReadOnly Property InferredNamesOpt As ImmutableArray(Of Boolean)
Get
Return _InferredNamesOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTupleLiteral(Me)
End Function
Public Function Update(inferredType As TupleTypeSymbol, argumentNamesOpt As ImmutableArray(Of String), inferredNamesOpt As ImmutableArray(Of Boolean), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundTupleLiteral
If inferredType IsNot Me.InferredType OrElse argumentNamesOpt <> Me.ArgumentNamesOpt OrElse inferredNamesOpt <> Me.InferredNamesOpt OrElse arguments <> Me.Arguments OrElse type IsNot Me.Type Then
Dim result = New BoundTupleLiteral(Me.Syntax, inferredType, argumentNamesOpt, inferredNamesOpt, arguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConvertedTupleLiteral
Inherits BoundTupleExpression
Public Sub New(syntax As SyntaxNode, naturalTypeOpt As TypeSymbol, arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConvertedTupleLiteral, syntax, arguments, type, hasErrors OrElse arguments.NonNullAndHasErrors())
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._NaturalTypeOpt = naturalTypeOpt
End Sub
Private ReadOnly _NaturalTypeOpt As TypeSymbol
Public ReadOnly Property NaturalTypeOpt As TypeSymbol
Get
Return _NaturalTypeOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConvertedTupleLiteral(Me)
End Function
Public Function Update(naturalTypeOpt As TypeSymbol, arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundConvertedTupleLiteral
If naturalTypeOpt IsNot Me.NaturalTypeOpt OrElse arguments <> Me.Arguments OrElse type IsNot Me.Type Then
Dim result = New BoundConvertedTupleLiteral(Me.Syntax, naturalTypeOpt, arguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundObjectCreationExpressionBase
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitializerOpt = initializerOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _InitializerOpt As BoundObjectInitializerExpressionBase
Public ReadOnly Property InitializerOpt As BoundObjectInitializerExpressionBase
Get
Return _InitializerOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundObjectCreationExpression
Inherits BoundObjectCreationExpressionBase
Public Sub New(syntax As SyntaxNode, constructorOpt As MethodSymbol, methodGroupOpt As BoundMethodGroup, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ObjectCreationExpression, syntax, initializerOpt, type, hasErrors OrElse methodGroupOpt.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors() OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ConstructorOpt = constructorOpt
Me._MethodGroupOpt = methodGroupOpt
Me._Arguments = arguments
Me._DefaultArguments = defaultArguments
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ConstructorOpt As MethodSymbol
Public ReadOnly Property ConstructorOpt As MethodSymbol
Get
Return _ConstructorOpt
End Get
End Property
Private ReadOnly _MethodGroupOpt As BoundMethodGroup
Public ReadOnly Property MethodGroupOpt As BoundMethodGroup
Get
Return _MethodGroupOpt
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
Private ReadOnly _DefaultArguments As BitVector
Public ReadOnly Property DefaultArguments As BitVector
Get
Return _DefaultArguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitObjectCreationExpression(Me)
End Function
Public Function Update(constructorOpt As MethodSymbol, methodGroupOpt As BoundMethodGroup, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundObjectCreationExpression
If constructorOpt IsNot Me.ConstructorOpt OrElse methodGroupOpt IsNot Me.MethodGroupOpt OrElse arguments <> Me.Arguments OrElse defaultArguments <> Me.DefaultArguments OrElse initializerOpt IsNot Me.InitializerOpt OrElse type IsNot Me.Type Then
Dim result = New BoundObjectCreationExpression(Me.Syntax, constructorOpt, methodGroupOpt, arguments, defaultArguments, initializerOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNoPiaObjectCreationExpression
Inherits BoundObjectCreationExpressionBase
Public Sub New(syntax As SyntaxNode, guidString As string, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NoPiaObjectCreationExpression, syntax, initializerOpt, type, hasErrors OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._GuidString = guidString
End Sub
Private ReadOnly _GuidString As string
Public ReadOnly Property GuidString As string
Get
Return _GuidString
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNoPiaObjectCreationExpression(Me)
End Function
Public Function Update(guidString As string, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundNoPiaObjectCreationExpression
If guidString IsNot Me.GuidString OrElse initializerOpt IsNot Me.InitializerOpt OrElse type IsNot Me.Type Then
Dim result = New BoundNoPiaObjectCreationExpression(Me.Syntax, guidString, initializerOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAnonymousTypeCreationExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binderOpt As Binder.AnonymousTypeCreationBinder, declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AnonymousTypeCreationExpression, syntax, type, hasErrors OrElse declarations.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors())
Debug.Assert(Not (declarations.IsDefault), "Field 'declarations' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._BinderOpt = binderOpt
Me._Declarations = declarations
Me._Arguments = arguments
End Sub
Private ReadOnly _BinderOpt As Binder.AnonymousTypeCreationBinder
Public ReadOnly Property BinderOpt As Binder.AnonymousTypeCreationBinder
Get
Return _BinderOpt
End Get
End Property
Private ReadOnly _Declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess)
Public ReadOnly Property Declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess)
Get
Return _Declarations
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAnonymousTypeCreationExpression(Me)
End Function
Public Function Update(binderOpt As Binder.AnonymousTypeCreationBinder, declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundAnonymousTypeCreationExpression
If binderOpt IsNot Me.BinderOpt OrElse declarations <> Me.Declarations OrElse arguments <> Me.Arguments OrElse type IsNot Me.Type Then
Dim result = New BoundAnonymousTypeCreationExpression(Me.Syntax, binderOpt, declarations, arguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAnonymousTypePropertyAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder.AnonymousTypeCreationBinder, propertyIndex As Integer, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.AnonymousTypePropertyAccess, syntax, type, hasErrors)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._PropertyIndex = propertyIndex
End Sub
Public Sub New(syntax As SyntaxNode, binder As Binder.AnonymousTypeCreationBinder, propertyIndex As Integer, type As TypeSymbol)
MyBase.New(BoundKind.AnonymousTypePropertyAccess, syntax, type)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._PropertyIndex = propertyIndex
End Sub
Private ReadOnly _Binder As Binder.AnonymousTypeCreationBinder
Public ReadOnly Property Binder As Binder.AnonymousTypeCreationBinder
Get
Return _Binder
End Get
End Property
Private ReadOnly _PropertyIndex As Integer
Public ReadOnly Property PropertyIndex As Integer
Get
Return _PropertyIndex
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAnonymousTypePropertyAccess(Me)
End Function
Public Function Update(binder As Binder.AnonymousTypeCreationBinder, propertyIndex As Integer, type As TypeSymbol) As BoundAnonymousTypePropertyAccess
If binder IsNot Me.Binder OrElse propertyIndex <> Me.PropertyIndex OrElse type IsNot Me.Type Then
Dim result = New BoundAnonymousTypePropertyAccess(Me.Syntax, binder, propertyIndex, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAnonymousTypeFieldInitializer
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder.AnonymousTypeFieldInitializerBinder, value As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AnonymousTypeFieldInitializer, syntax, type, hasErrors OrElse value.NonNullAndHasErrors())
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Value = value
End Sub
Private ReadOnly _Binder As Binder.AnonymousTypeFieldInitializerBinder
Public ReadOnly Property Binder As Binder.AnonymousTypeFieldInitializerBinder
Get
Return _Binder
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAnonymousTypeFieldInitializer(Me)
End Function
Public Function Update(binder As Binder.AnonymousTypeFieldInitializerBinder, value As BoundExpression, type As TypeSymbol) As BoundAnonymousTypeFieldInitializer
If binder IsNot Me.Binder OrElse value IsNot Me.Value OrElse type IsNot Me.Type Then
Dim result = New BoundAnonymousTypeFieldInitializer(Me.Syntax, binder, value, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundObjectInitializerExpressionBase
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PlaceholderOpt = placeholderOpt
Me._Initializers = initializers
End Sub
Private ReadOnly _PlaceholderOpt As BoundWithLValueExpressionPlaceholder
Public ReadOnly Property PlaceholderOpt As BoundWithLValueExpressionPlaceholder
Get
Return _PlaceholderOpt
End Get
End Property
Private ReadOnly _Initializers As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Initializers As ImmutableArray(Of BoundExpression)
Get
Return _Initializers
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundObjectInitializerExpression
Inherits BoundObjectInitializerExpressionBase
Public Sub New(syntax As SyntaxNode, createTemporaryLocalForInitialization As Boolean, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ObjectInitializerExpression, syntax, placeholderOpt, initializers, type, hasErrors OrElse placeholderOpt.NonNullAndHasErrors() OrElse initializers.NonNullAndHasErrors())
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CreateTemporaryLocalForInitialization = createTemporaryLocalForInitialization
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _CreateTemporaryLocalForInitialization As Boolean
Public ReadOnly Property CreateTemporaryLocalForInitialization As Boolean
Get
Return _CreateTemporaryLocalForInitialization
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitObjectInitializerExpression(Me)
End Function
Public Function Update(createTemporaryLocalForInitialization As Boolean, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundObjectInitializerExpression
If createTemporaryLocalForInitialization <> Me.CreateTemporaryLocalForInitialization OrElse placeholderOpt IsNot Me.PlaceholderOpt OrElse initializers <> Me.Initializers OrElse type IsNot Me.Type Then
Dim result = New BoundObjectInitializerExpression(Me.Syntax, createTemporaryLocalForInitialization, placeholderOpt, initializers, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCollectionInitializerExpression
Inherits BoundObjectInitializerExpressionBase
Public Sub New(syntax As SyntaxNode, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CollectionInitializerExpression, syntax, placeholderOpt, initializers, type, hasErrors OrElse placeholderOpt.NonNullAndHasErrors() OrElse initializers.NonNullAndHasErrors())
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCollectionInitializerExpression(Me)
End Function
Public Function Update(placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundCollectionInitializerExpression
If placeholderOpt IsNot Me.PlaceholderOpt OrElse initializers <> Me.Initializers OrElse type IsNot Me.Type Then
Dim result = New BoundCollectionInitializerExpression(Me.Syntax, placeholderOpt, initializers, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNewT
Inherits BoundObjectCreationExpressionBase
Public Sub New(syntax As SyntaxNode, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NewT, syntax, initializerOpt, type, hasErrors OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNewT(Me)
End Function
Public Function Update(initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundNewT
If initializerOpt IsNot Me.InitializerOpt OrElse type IsNot Me.Type Then
Dim result = New BoundNewT(Me.Syntax, initializerOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDelegateCreationExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOpt As BoundExpression, method As MethodSymbol, relaxationLambdaOpt As BoundLambda, relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder, methodGroupOpt As BoundMethodGroup, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DelegateCreationExpression, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors() OrElse relaxationLambdaOpt.NonNullAndHasErrors() OrElse relaxationReceiverPlaceholderOpt.NonNullAndHasErrors() OrElse methodGroupOpt.NonNullAndHasErrors())
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOpt = receiverOpt
Me._Method = method
Me._RelaxationLambdaOpt = relaxationLambdaOpt
Me._RelaxationReceiverPlaceholderOpt = relaxationReceiverPlaceholderOpt
Me._MethodGroupOpt = methodGroupOpt
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
Private ReadOnly _RelaxationLambdaOpt As BoundLambda
Public ReadOnly Property RelaxationLambdaOpt As BoundLambda
Get
Return _RelaxationLambdaOpt
End Get
End Property
Private ReadOnly _RelaxationReceiverPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property RelaxationReceiverPlaceholderOpt As BoundRValuePlaceholder
Get
Return _RelaxationReceiverPlaceholderOpt
End Get
End Property
Private ReadOnly _MethodGroupOpt As BoundMethodGroup
Public ReadOnly Property MethodGroupOpt As BoundMethodGroup
Get
Return _MethodGroupOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDelegateCreationExpression(Me)
End Function
Public Function Update(receiverOpt As BoundExpression, method As MethodSymbol, relaxationLambdaOpt As BoundLambda, relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder, methodGroupOpt As BoundMethodGroup, type As TypeSymbol) As BoundDelegateCreationExpression
If receiverOpt IsNot Me.ReceiverOpt OrElse method IsNot Me.Method OrElse relaxationLambdaOpt IsNot Me.RelaxationLambdaOpt OrElse relaxationReceiverPlaceholderOpt IsNot Me.RelaxationReceiverPlaceholderOpt OrElse methodGroupOpt IsNot Me.MethodGroupOpt OrElse type IsNot Me.Type Then
Dim result = New BoundDelegateCreationExpression(Me.Syntax, receiverOpt, method, relaxationLambdaOpt, relaxationReceiverPlaceholderOpt, methodGroupOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayCreation
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, isParamArrayArgument As Boolean, bounds As ImmutableArray(Of BoundExpression), initializerOpt As BoundArrayInitialization, arrayLiteralOpt As BoundArrayLiteral, arrayLiteralConversion As ConversionKind, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayCreation, syntax, type, hasErrors OrElse bounds.NonNullAndHasErrors() OrElse initializerOpt.NonNullAndHasErrors() OrElse arrayLiteralOpt.NonNullAndHasErrors())
Debug.Assert(Not (bounds.IsDefault), "Field 'bounds' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsParamArrayArgument = isParamArrayArgument
Me._Bounds = bounds
Me._InitializerOpt = initializerOpt
Me._ArrayLiteralOpt = arrayLiteralOpt
Me._ArrayLiteralConversion = arrayLiteralConversion
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _IsParamArrayArgument As Boolean
Public ReadOnly Property IsParamArrayArgument As Boolean
Get
Return _IsParamArrayArgument
End Get
End Property
Private ReadOnly _Bounds As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Bounds As ImmutableArray(Of BoundExpression)
Get
Return _Bounds
End Get
End Property
Private ReadOnly _InitializerOpt As BoundArrayInitialization
Public ReadOnly Property InitializerOpt As BoundArrayInitialization
Get
Return _InitializerOpt
End Get
End Property
Private ReadOnly _ArrayLiteralOpt As BoundArrayLiteral
Public ReadOnly Property ArrayLiteralOpt As BoundArrayLiteral
Get
Return _ArrayLiteralOpt
End Get
End Property
Private ReadOnly _ArrayLiteralConversion As ConversionKind
Public ReadOnly Property ArrayLiteralConversion As ConversionKind
Get
Return _ArrayLiteralConversion
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayCreation(Me)
End Function
Public Function Update(isParamArrayArgument As Boolean, bounds As ImmutableArray(Of BoundExpression), initializerOpt As BoundArrayInitialization, arrayLiteralOpt As BoundArrayLiteral, arrayLiteralConversion As ConversionKind, type As TypeSymbol) As BoundArrayCreation
If isParamArrayArgument <> Me.IsParamArrayArgument OrElse bounds <> Me.Bounds OrElse initializerOpt IsNot Me.InitializerOpt OrElse arrayLiteralOpt IsNot Me.ArrayLiteralOpt OrElse arrayLiteralConversion <> Me.ArrayLiteralConversion OrElse type IsNot Me.Type Then
Dim result = New BoundArrayCreation(Me.Syntax, isParamArrayArgument, bounds, initializerOpt, arrayLiteralOpt, arrayLiteralConversion, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayLiteral
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, hasDominantType As Boolean, numberOfCandidates As Integer, inferredType As ArrayTypeSymbol, bounds As ImmutableArray(Of BoundExpression), initializer As BoundArrayInitialization, binder As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayLiteral, syntax, Nothing, hasErrors OrElse bounds.NonNullAndHasErrors() OrElse initializer.NonNullAndHasErrors())
Debug.Assert(inferredType IsNot Nothing, "Field 'inferredType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (bounds.IsDefault), "Field 'bounds' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initializer IsNot Nothing, "Field 'initializer' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._HasDominantType = hasDominantType
Me._NumberOfCandidates = numberOfCandidates
Me._InferredType = inferredType
Me._Bounds = bounds
Me._Initializer = initializer
Me._Binder = binder
End Sub
Private ReadOnly _HasDominantType As Boolean
Public ReadOnly Property HasDominantType As Boolean
Get
Return _HasDominantType
End Get
End Property
Private ReadOnly _NumberOfCandidates As Integer
Public ReadOnly Property NumberOfCandidates As Integer
Get
Return _NumberOfCandidates
End Get
End Property
Private ReadOnly _InferredType As ArrayTypeSymbol
Public ReadOnly Property InferredType As ArrayTypeSymbol
Get
Return _InferredType
End Get
End Property
Private ReadOnly _Bounds As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Bounds As ImmutableArray(Of BoundExpression)
Get
Return _Bounds
End Get
End Property
Private ReadOnly _Initializer As BoundArrayInitialization
Public ReadOnly Property Initializer As BoundArrayInitialization
Get
Return _Initializer
End Get
End Property
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayLiteral(Me)
End Function
Public Function Update(hasDominantType As Boolean, numberOfCandidates As Integer, inferredType As ArrayTypeSymbol, bounds As ImmutableArray(Of BoundExpression), initializer As BoundArrayInitialization, binder As Binder) As BoundArrayLiteral
If hasDominantType <> Me.HasDominantType OrElse numberOfCandidates <> Me.NumberOfCandidates OrElse inferredType IsNot Me.InferredType OrElse bounds <> Me.Bounds OrElse initializer IsNot Me.Initializer OrElse binder IsNot Me.Binder Then
Dim result = New BoundArrayLiteral(Me.Syntax, hasDominantType, numberOfCandidates, inferredType, bounds, initializer, binder, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayInitialization
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayInitialization, syntax, type, hasErrors OrElse initializers.NonNullAndHasErrors())
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Initializers = initializers
End Sub
Private ReadOnly _Initializers As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Initializers As ImmutableArray(Of BoundExpression)
Get
Return _Initializers
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayInitialization(Me)
End Function
Public Function Update(initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundArrayInitialization
If initializers <> Me.Initializers OrElse type IsNot Me.Type Then
Dim result = New BoundArrayInitialization(Me.Syntax, initializers, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundFieldAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOpt As BoundExpression, fieldSymbol As FieldSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, constantsInProgressOpt As ConstantFieldsInProgress, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.FieldAccess, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(fieldSymbol IsNot Nothing, "Field 'fieldSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOpt = receiverOpt
Me._FieldSymbol = fieldSymbol
Me._IsLValue = isLValue
Me._SuppressVirtualCalls = suppressVirtualCalls
Me._ConstantsInProgressOpt = constantsInProgressOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _FieldSymbol As FieldSymbol
Public ReadOnly Property FieldSymbol As FieldSymbol
Get
Return _FieldSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _SuppressVirtualCalls As Boolean
Public Overrides ReadOnly Property SuppressVirtualCalls As Boolean
Get
Return _SuppressVirtualCalls
End Get
End Property
Private ReadOnly _ConstantsInProgressOpt As ConstantFieldsInProgress
Public ReadOnly Property ConstantsInProgressOpt As ConstantFieldsInProgress
Get
Return _ConstantsInProgressOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitFieldAccess(Me)
End Function
Public Function Update(receiverOpt As BoundExpression, fieldSymbol As FieldSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, constantsInProgressOpt As ConstantFieldsInProgress, type As TypeSymbol) As BoundFieldAccess
If receiverOpt IsNot Me.ReceiverOpt OrElse fieldSymbol IsNot Me.FieldSymbol OrElse isLValue <> Me.IsLValue OrElse suppressVirtualCalls <> Me.SuppressVirtualCalls OrElse constantsInProgressOpt IsNot Me.ConstantsInProgressOpt OrElse type IsNot Me.Type Then
Dim result = New BoundFieldAccess(Me.Syntax, receiverOpt, fieldSymbol, isLValue, suppressVirtualCalls, constantsInProgressOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPropertyAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, propertySymbol As PropertySymbol, propertyGroupOpt As BoundPropertyGroup, accessKind As PropertyAccessKind, isWriteable As Boolean, isLValue As Boolean, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.PropertyAccess, syntax, type, hasErrors OrElse propertyGroupOpt.NonNullAndHasErrors() OrElse receiverOpt.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors())
Debug.Assert(propertySymbol IsNot Nothing, "Field 'propertySymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PropertySymbol = propertySymbol
Me._PropertyGroupOpt = propertyGroupOpt
Me._AccessKind = accessKind
Me._IsWriteable = isWriteable
Me._IsLValue = isLValue
Me._ReceiverOpt = receiverOpt
Me._Arguments = arguments
Me._DefaultArguments = defaultArguments
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _PropertySymbol As PropertySymbol
Public ReadOnly Property PropertySymbol As PropertySymbol
Get
Return _PropertySymbol
End Get
End Property
Private ReadOnly _PropertyGroupOpt As BoundPropertyGroup
Public ReadOnly Property PropertyGroupOpt As BoundPropertyGroup
Get
Return _PropertyGroupOpt
End Get
End Property
Private ReadOnly _AccessKind As PropertyAccessKind
Public ReadOnly Property AccessKind As PropertyAccessKind
Get
Return _AccessKind
End Get
End Property
Private ReadOnly _IsWriteable As Boolean
Public ReadOnly Property IsWriteable As Boolean
Get
Return _IsWriteable
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
Private ReadOnly _DefaultArguments As BitVector
Public ReadOnly Property DefaultArguments As BitVector
Get
Return _DefaultArguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPropertyAccess(Me)
End Function
Public Function Update(propertySymbol As PropertySymbol, propertyGroupOpt As BoundPropertyGroup, accessKind As PropertyAccessKind, isWriteable As Boolean, isLValue As Boolean, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, type As TypeSymbol) As BoundPropertyAccess
If propertySymbol IsNot Me.PropertySymbol OrElse propertyGroupOpt IsNot Me.PropertyGroupOpt OrElse accessKind <> Me.AccessKind OrElse isWriteable <> Me.IsWriteable OrElse isLValue <> Me.IsLValue OrElse receiverOpt IsNot Me.ReceiverOpt OrElse arguments <> Me.Arguments OrElse defaultArguments <> Me.DefaultArguments OrElse type IsNot Me.Type Then
Dim result = New BoundPropertyAccess(Me.Syntax, propertySymbol, propertyGroupOpt, accessKind, isWriteable, isLValue, receiverOpt, arguments, defaultArguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundEventAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOpt As BoundExpression, eventSymbol As EventSymbol, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.EventAccess, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(eventSymbol IsNot Nothing, "Field 'eventSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOpt = receiverOpt
Me._EventSymbol = eventSymbol
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _EventSymbol As EventSymbol
Public ReadOnly Property EventSymbol As EventSymbol
Get
Return _EventSymbol
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitEventAccess(Me)
End Function
Public Function Update(receiverOpt As BoundExpression, eventSymbol As EventSymbol, type As TypeSymbol) As BoundEventAccess
If receiverOpt IsNot Me.ReceiverOpt OrElse eventSymbol IsNot Me.EventSymbol OrElse type IsNot Me.Type Then
Dim result = New BoundEventAccess(Me.Syntax, receiverOpt, eventSymbol, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBlock
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statementListSyntax As SyntaxList(Of StatementSyntax), locals As ImmutableArray(Of LocalSymbol), statements As ImmutableArray(Of BoundStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Block, syntax, hasErrors OrElse statements.NonNullAndHasErrors())
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (statements.IsDefault), "Field 'statements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._StatementListSyntax = statementListSyntax
Me._Locals = locals
Me._Statements = statements
End Sub
Private ReadOnly _StatementListSyntax As SyntaxList(Of StatementSyntax)
Public ReadOnly Property StatementListSyntax As SyntaxList(Of StatementSyntax)
Get
Return _StatementListSyntax
End Get
End Property
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
Private ReadOnly _Statements As ImmutableArray(Of BoundStatement)
Public ReadOnly Property Statements As ImmutableArray(Of BoundStatement)
Get
Return _Statements
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBlock(Me)
End Function
Public Function Update(statementListSyntax As SyntaxList(Of StatementSyntax), locals As ImmutableArray(Of LocalSymbol), statements As ImmutableArray(Of BoundStatement)) As BoundBlock
If statementListSyntax <> Me.StatementListSyntax OrElse locals <> Me.Locals OrElse statements <> Me.Statements Then
Dim result = New BoundBlock(Me.Syntax, statementListSyntax, locals, statements, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundStateMachineScope
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, fields As ImmutableArray(Of FieldSymbol), statement As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.StateMachineScope, syntax, hasErrors OrElse statement.NonNullAndHasErrors())
Debug.Assert(Not (fields.IsDefault), "Field 'fields' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(statement IsNot Nothing, "Field 'statement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Fields = fields
Me._Statement = statement
End Sub
Private ReadOnly _Fields As ImmutableArray(Of FieldSymbol)
Public ReadOnly Property Fields As ImmutableArray(Of FieldSymbol)
Get
Return _Fields
End Get
End Property
Private ReadOnly _Statement As BoundStatement
Public ReadOnly Property Statement As BoundStatement
Get
Return _Statement
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitStateMachineScope(Me)
End Function
Public Function Update(fields As ImmutableArray(Of FieldSymbol), statement As BoundStatement) As BoundStateMachineScope
If fields <> Me.Fields OrElse statement IsNot Me.Statement Then
Dim result = New BoundStateMachineScope(Me.Syntax, fields, statement, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundLocalDeclarationBase
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend NotInheritable Class BoundLocalDeclaration
Inherits BoundLocalDeclarationBase
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, declarationInitializerOpt As BoundExpression, identifierInitializerOpt As BoundArrayCreation, initializedByAsNew As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LocalDeclaration, syntax, hasErrors OrElse declarationInitializerOpt.NonNullAndHasErrors() OrElse identifierInitializerOpt.NonNullAndHasErrors())
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._DeclarationInitializerOpt = declarationInitializerOpt
Me._IdentifierInitializerOpt = identifierInitializerOpt
Me._InitializedByAsNew = initializedByAsNew
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LocalSymbol As LocalSymbol
Public ReadOnly Property LocalSymbol As LocalSymbol
Get
Return _LocalSymbol
End Get
End Property
Private ReadOnly _DeclarationInitializerOpt As BoundExpression
Public ReadOnly Property DeclarationInitializerOpt As BoundExpression
Get
Return _DeclarationInitializerOpt
End Get
End Property
Private ReadOnly _IdentifierInitializerOpt As BoundArrayCreation
Public ReadOnly Property IdentifierInitializerOpt As BoundArrayCreation
Get
Return _IdentifierInitializerOpt
End Get
End Property
Private ReadOnly _InitializedByAsNew As Boolean
Public ReadOnly Property InitializedByAsNew As Boolean
Get
Return _InitializedByAsNew
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLocalDeclaration(Me)
End Function
Public Function Update(localSymbol As LocalSymbol, declarationInitializerOpt As BoundExpression, identifierInitializerOpt As BoundArrayCreation, initializedByAsNew As Boolean) As BoundLocalDeclaration
If localSymbol IsNot Me.LocalSymbol OrElse declarationInitializerOpt IsNot Me.DeclarationInitializerOpt OrElse identifierInitializerOpt IsNot Me.IdentifierInitializerOpt OrElse initializedByAsNew <> Me.InitializedByAsNew Then
Dim result = New BoundLocalDeclaration(Me.Syntax, localSymbol, declarationInitializerOpt, identifierInitializerOpt, initializedByAsNew, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAsNewLocalDeclarations
Inherits BoundLocalDeclarationBase
Public Sub New(syntax As SyntaxNode, localDeclarations As ImmutableArray(Of BoundLocalDeclaration), initializer As BoundExpression, binder As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AsNewLocalDeclarations, syntax, hasErrors OrElse localDeclarations.NonNullAndHasErrors() OrElse initializer.NonNullAndHasErrors())
Debug.Assert(Not (localDeclarations.IsDefault), "Field 'localDeclarations' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initializer IsNot Nothing, "Field 'initializer' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalDeclarations = localDeclarations
Me._Initializer = initializer
Me._Binder = binder
End Sub
Private ReadOnly _LocalDeclarations As ImmutableArray(Of BoundLocalDeclaration)
Public ReadOnly Property LocalDeclarations As ImmutableArray(Of BoundLocalDeclaration)
Get
Return _LocalDeclarations
End Get
End Property
Private ReadOnly _Initializer As BoundExpression
Public ReadOnly Property Initializer As BoundExpression
Get
Return _Initializer
End Get
End Property
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAsNewLocalDeclarations(Me)
End Function
Public Function Update(localDeclarations As ImmutableArray(Of BoundLocalDeclaration), initializer As BoundExpression, binder As Binder) As BoundAsNewLocalDeclarations
If localDeclarations <> Me.LocalDeclarations OrElse initializer IsNot Me.Initializer OrElse binder IsNot Me.Binder Then
Dim result = New BoundAsNewLocalDeclarations(Me.Syntax, localDeclarations, initializer, binder, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDimStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, localDeclarations As ImmutableArray(Of BoundLocalDeclarationBase), initializerOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DimStatement, syntax, hasErrors OrElse localDeclarations.NonNullAndHasErrors() OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(Not (localDeclarations.IsDefault), "Field 'localDeclarations' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalDeclarations = localDeclarations
Me._InitializerOpt = initializerOpt
End Sub
Private ReadOnly _LocalDeclarations As ImmutableArray(Of BoundLocalDeclarationBase)
Public ReadOnly Property LocalDeclarations As ImmutableArray(Of BoundLocalDeclarationBase)
Get
Return _LocalDeclarations
End Get
End Property
Private ReadOnly _InitializerOpt As BoundExpression
Public ReadOnly Property InitializerOpt As BoundExpression
Get
Return _InitializerOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDimStatement(Me)
End Function
Public Function Update(localDeclarations As ImmutableArray(Of BoundLocalDeclarationBase), initializerOpt As BoundExpression) As BoundDimStatement
If localDeclarations <> Me.LocalDeclarations OrElse initializerOpt IsNot Me.InitializerOpt Then
Dim result = New BoundDimStatement(Me.Syntax, localDeclarations, initializerOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend Class BoundInitializer
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyBase.New(BoundKind.Initializer, syntax, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode)
MyBase.New(BoundKind.Initializer, syntax)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInitializer(Me)
End Function
End Class
Partial Friend MustInherit Class BoundFieldOrPropertyInitializer
Inherits BoundInitializer
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, hasErrors)
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._MemberAccessExpressionOpt = memberAccessExpressionOpt
Me._InitialValue = initialValue
Me._BinderOpt = binderOpt
End Sub
Private ReadOnly _MemberAccessExpressionOpt As BoundExpression
Public ReadOnly Property MemberAccessExpressionOpt As BoundExpression
Get
Return _MemberAccessExpressionOpt
End Get
End Property
Private ReadOnly _InitialValue As BoundExpression
Public ReadOnly Property InitialValue As BoundExpression
Get
Return _InitialValue
End Get
End Property
Private ReadOnly _BinderOpt As Binder
Public ReadOnly Property BinderOpt As Binder
Get
Return _BinderOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundFieldInitializer
Inherits BoundFieldOrPropertyInitializer
Public Sub New(syntax As SyntaxNode, initializedFields As ImmutableArray(Of FieldSymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.FieldInitializer, syntax, memberAccessExpressionOpt, initialValue, binderOpt, hasErrors OrElse memberAccessExpressionOpt.NonNullAndHasErrors() OrElse initialValue.NonNullAndHasErrors())
Debug.Assert(Not (initializedFields.IsDefault), "Field 'initializedFields' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitializedFields = initializedFields
End Sub
Private ReadOnly _InitializedFields As ImmutableArray(Of FieldSymbol)
Public ReadOnly Property InitializedFields As ImmutableArray(Of FieldSymbol)
Get
Return _InitializedFields
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitFieldInitializer(Me)
End Function
Public Function Update(initializedFields As ImmutableArray(Of FieldSymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder) As BoundFieldInitializer
If initializedFields <> Me.InitializedFields OrElse memberAccessExpressionOpt IsNot Me.MemberAccessExpressionOpt OrElse initialValue IsNot Me.InitialValue OrElse binderOpt IsNot Me.BinderOpt Then
Dim result = New BoundFieldInitializer(Me.Syntax, initializedFields, memberAccessExpressionOpt, initialValue, binderOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPropertyInitializer
Inherits BoundFieldOrPropertyInitializer
Public Sub New(syntax As SyntaxNode, initializedProperties As ImmutableArray(Of PropertySymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.PropertyInitializer, syntax, memberAccessExpressionOpt, initialValue, binderOpt, hasErrors OrElse memberAccessExpressionOpt.NonNullAndHasErrors() OrElse initialValue.NonNullAndHasErrors())
Debug.Assert(Not (initializedProperties.IsDefault), "Field 'initializedProperties' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitializedProperties = initializedProperties
End Sub
Private ReadOnly _InitializedProperties As ImmutableArray(Of PropertySymbol)
Public ReadOnly Property InitializedProperties As ImmutableArray(Of PropertySymbol)
Get
Return _InitializedProperties
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPropertyInitializer(Me)
End Function
Public Function Update(initializedProperties As ImmutableArray(Of PropertySymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder) As BoundPropertyInitializer
If initializedProperties <> Me.InitializedProperties OrElse memberAccessExpressionOpt IsNot Me.MemberAccessExpressionOpt OrElse initialValue IsNot Me.InitialValue OrElse binderOpt IsNot Me.BinderOpt Then
Dim result = New BoundPropertyInitializer(Me.Syntax, initializedProperties, memberAccessExpressionOpt, initialValue, binderOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundParameterEqualsValue
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, parameter As ParameterSymbol, value As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ParameterEqualsValue, syntax, hasErrors OrElse value.NonNullAndHasErrors())
Debug.Assert(parameter IsNot Nothing, "Field 'parameter' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Parameter = parameter
Me._Value = value
End Sub
Private ReadOnly _Parameter As ParameterSymbol
Public ReadOnly Property Parameter As ParameterSymbol
Get
Return _Parameter
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitParameterEqualsValue(Me)
End Function
Public Function Update(parameter As ParameterSymbol, value As BoundExpression) As BoundParameterEqualsValue
If parameter IsNot Me.Parameter OrElse value IsNot Me.Value Then
Dim result = New BoundParameterEqualsValue(Me.Syntax, parameter, value, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGlobalStatementInitializer
Inherits BoundInitializer
Public Sub New(syntax As SyntaxNode, statement As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GlobalStatementInitializer, syntax, hasErrors OrElse statement.NonNullAndHasErrors())
Debug.Assert(statement IsNot Nothing, "Field 'statement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Statement = statement
End Sub
Private ReadOnly _Statement As BoundStatement
Public ReadOnly Property Statement As BoundStatement
Get
Return _Statement
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGlobalStatementInitializer(Me)
End Function
Public Function Update(statement As BoundStatement) As BoundGlobalStatementInitializer
If statement IsNot Me.Statement Then
Dim result = New BoundGlobalStatementInitializer(Me.Syntax, statement, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSequence
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, locals As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression), valueOpt As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Sequence, syntax, type, hasErrors OrElse sideEffects.NonNullAndHasErrors() OrElse valueOpt.NonNullAndHasErrors())
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (sideEffects.IsDefault), "Field 'sideEffects' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Locals = locals
Me._SideEffects = sideEffects
Me._ValueOpt = valueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
Private ReadOnly _SideEffects As ImmutableArray(Of BoundExpression)
Public ReadOnly Property SideEffects As ImmutableArray(Of BoundExpression)
Get
Return _SideEffects
End Get
End Property
Private ReadOnly _ValueOpt As BoundExpression
Public ReadOnly Property ValueOpt As BoundExpression
Get
Return _ValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequence(Me)
End Function
Public Function Update(locals As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression), valueOpt As BoundExpression, type As TypeSymbol) As BoundSequence
If locals <> Me.Locals OrElse sideEffects <> Me.SideEffects OrElse valueOpt IsNot Me.ValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundSequence(Me.Syntax, locals, sideEffects, valueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundExpressionStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ExpressionStatement, syntax, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitExpressionStatement(Me)
End Function
Public Function Update(expression As BoundExpression) As BoundExpressionStatement
If expression IsNot Me.Expression Then
Dim result = New BoundExpressionStatement(Me.Syntax, expression, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundIfStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, consequence As BoundStatement, alternativeOpt As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.IfStatement, syntax, hasErrors OrElse condition.NonNullAndHasErrors() OrElse consequence.NonNullAndHasErrors() OrElse alternativeOpt.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(consequence IsNot Nothing, "Field 'consequence' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._Consequence = consequence
Me._AlternativeOpt = alternativeOpt
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _Consequence As BoundStatement
Public ReadOnly Property Consequence As BoundStatement
Get
Return _Consequence
End Get
End Property
Private ReadOnly _AlternativeOpt As BoundStatement
Public ReadOnly Property AlternativeOpt As BoundStatement
Get
Return _AlternativeOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitIfStatement(Me)
End Function
Public Function Update(condition As BoundExpression, consequence As BoundStatement, alternativeOpt As BoundStatement) As BoundIfStatement
If condition IsNot Me.Condition OrElse consequence IsNot Me.Consequence OrElse alternativeOpt IsNot Me.AlternativeOpt Then
Dim result = New BoundIfStatement(Me.Syntax, condition, consequence, alternativeOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSelectStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expressionStatement As BoundExpressionStatement, exprPlaceholderOpt As BoundRValuePlaceholder, caseBlocks As ImmutableArray(Of BoundCaseBlock), recommendSwitchTable As Boolean, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SelectStatement, syntax, hasErrors OrElse expressionStatement.NonNullAndHasErrors() OrElse exprPlaceholderOpt.NonNullAndHasErrors() OrElse caseBlocks.NonNullAndHasErrors())
Debug.Assert(expressionStatement IsNot Nothing, "Field 'expressionStatement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (caseBlocks.IsDefault), "Field 'caseBlocks' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ExpressionStatement = expressionStatement
Me._ExprPlaceholderOpt = exprPlaceholderOpt
Me._CaseBlocks = caseBlocks
Me._RecommendSwitchTable = recommendSwitchTable
Me._ExitLabel = exitLabel
End Sub
Private ReadOnly _ExpressionStatement As BoundExpressionStatement
Public ReadOnly Property ExpressionStatement As BoundExpressionStatement
Get
Return _ExpressionStatement
End Get
End Property
Private ReadOnly _ExprPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property ExprPlaceholderOpt As BoundRValuePlaceholder
Get
Return _ExprPlaceholderOpt
End Get
End Property
Private ReadOnly _CaseBlocks As ImmutableArray(Of BoundCaseBlock)
Public ReadOnly Property CaseBlocks As ImmutableArray(Of BoundCaseBlock)
Get
Return _CaseBlocks
End Get
End Property
Private ReadOnly _RecommendSwitchTable As Boolean
Public ReadOnly Property RecommendSwitchTable As Boolean
Get
Return _RecommendSwitchTable
End Get
End Property
Private ReadOnly _ExitLabel As LabelSymbol
Public ReadOnly Property ExitLabel As LabelSymbol
Get
Return _ExitLabel
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSelectStatement(Me)
End Function
Public Function Update(expressionStatement As BoundExpressionStatement, exprPlaceholderOpt As BoundRValuePlaceholder, caseBlocks As ImmutableArray(Of BoundCaseBlock), recommendSwitchTable As Boolean, exitLabel As LabelSymbol) As BoundSelectStatement
If expressionStatement IsNot Me.ExpressionStatement OrElse exprPlaceholderOpt IsNot Me.ExprPlaceholderOpt OrElse caseBlocks <> Me.CaseBlocks OrElse recommendSwitchTable <> Me.RecommendSwitchTable OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundSelectStatement(Me.Syntax, expressionStatement, exprPlaceholderOpt, caseBlocks, recommendSwitchTable, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCaseBlock
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, caseStatement As BoundCaseStatement, body As BoundBlock, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CaseBlock, syntax, hasErrors OrElse caseStatement.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(caseStatement IsNot Nothing, "Field 'caseStatement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CaseStatement = caseStatement
Me._Body = body
End Sub
Private ReadOnly _CaseStatement As BoundCaseStatement
Public ReadOnly Property CaseStatement As BoundCaseStatement
Get
Return _CaseStatement
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCaseBlock(Me)
End Function
Public Function Update(caseStatement As BoundCaseStatement, body As BoundBlock) As BoundCaseBlock
If caseStatement IsNot Me.CaseStatement OrElse body IsNot Me.Body Then
Dim result = New BoundCaseBlock(Me.Syntax, caseStatement, body, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCaseStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, caseClauses As ImmutableArray(Of BoundCaseClause), conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CaseStatement, syntax, hasErrors OrElse caseClauses.NonNullAndHasErrors() OrElse conditionOpt.NonNullAndHasErrors())
Debug.Assert(Not (caseClauses.IsDefault), "Field 'caseClauses' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CaseClauses = caseClauses
Me._ConditionOpt = conditionOpt
End Sub
Private ReadOnly _CaseClauses As ImmutableArray(Of BoundCaseClause)
Public ReadOnly Property CaseClauses As ImmutableArray(Of BoundCaseClause)
Get
Return _CaseClauses
End Get
End Property
Private ReadOnly _ConditionOpt As BoundExpression
Public ReadOnly Property ConditionOpt As BoundExpression
Get
Return _ConditionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCaseStatement(Me)
End Function
Public Function Update(caseClauses As ImmutableArray(Of BoundCaseClause), conditionOpt As BoundExpression) As BoundCaseStatement
If caseClauses <> Me.CaseClauses OrElse conditionOpt IsNot Me.ConditionOpt Then
Dim result = New BoundCaseStatement(Me.Syntax, caseClauses, conditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundCaseClause
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend MustInherit Class BoundSingleValueCaseClause
Inherits BoundCaseClause
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, valueOpt As BoundExpression, conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, hasErrors)
Me._ValueOpt = valueOpt
Me._ConditionOpt = conditionOpt
End Sub
Private ReadOnly _ValueOpt As BoundExpression
Public ReadOnly Property ValueOpt As BoundExpression
Get
Return _ValueOpt
End Get
End Property
Private ReadOnly _ConditionOpt As BoundExpression
Public ReadOnly Property ConditionOpt As BoundExpression
Get
Return _ConditionOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundSimpleCaseClause
Inherits BoundSingleValueCaseClause
Public Sub New(syntax As SyntaxNode, valueOpt As BoundExpression, conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SimpleCaseClause, syntax, valueOpt, conditionOpt, hasErrors OrElse valueOpt.NonNullAndHasErrors() OrElse conditionOpt.NonNullAndHasErrors())
Validate()
End Sub
Private Partial Sub Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSimpleCaseClause(Me)
End Function
Public Function Update(valueOpt As BoundExpression, conditionOpt As BoundExpression) As BoundSimpleCaseClause
If valueOpt IsNot Me.ValueOpt OrElse conditionOpt IsNot Me.ConditionOpt Then
Dim result = New BoundSimpleCaseClause(Me.Syntax, valueOpt, conditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRangeCaseClause
Inherits BoundCaseClause
Public Sub New(syntax As SyntaxNode, lowerBoundOpt As BoundExpression, upperBoundOpt As BoundExpression, lowerBoundConditionOpt As BoundExpression, upperBoundConditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RangeCaseClause, syntax, hasErrors OrElse lowerBoundOpt.NonNullAndHasErrors() OrElse upperBoundOpt.NonNullAndHasErrors() OrElse lowerBoundConditionOpt.NonNullAndHasErrors() OrElse upperBoundConditionOpt.NonNullAndHasErrors())
Me._LowerBoundOpt = lowerBoundOpt
Me._UpperBoundOpt = upperBoundOpt
Me._LowerBoundConditionOpt = lowerBoundConditionOpt
Me._UpperBoundConditionOpt = upperBoundConditionOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LowerBoundOpt As BoundExpression
Public ReadOnly Property LowerBoundOpt As BoundExpression
Get
Return _LowerBoundOpt
End Get
End Property
Private ReadOnly _UpperBoundOpt As BoundExpression
Public ReadOnly Property UpperBoundOpt As BoundExpression
Get
Return _UpperBoundOpt
End Get
End Property
Private ReadOnly _LowerBoundConditionOpt As BoundExpression
Public ReadOnly Property LowerBoundConditionOpt As BoundExpression
Get
Return _LowerBoundConditionOpt
End Get
End Property
Private ReadOnly _UpperBoundConditionOpt As BoundExpression
Public ReadOnly Property UpperBoundConditionOpt As BoundExpression
Get
Return _UpperBoundConditionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRangeCaseClause(Me)
End Function
Public Function Update(lowerBoundOpt As BoundExpression, upperBoundOpt As BoundExpression, lowerBoundConditionOpt As BoundExpression, upperBoundConditionOpt As BoundExpression) As BoundRangeCaseClause
If lowerBoundOpt IsNot Me.LowerBoundOpt OrElse upperBoundOpt IsNot Me.UpperBoundOpt OrElse lowerBoundConditionOpt IsNot Me.LowerBoundConditionOpt OrElse upperBoundConditionOpt IsNot Me.UpperBoundConditionOpt Then
Dim result = New BoundRangeCaseClause(Me.Syntax, lowerBoundOpt, upperBoundOpt, lowerBoundConditionOpt, upperBoundConditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRelationalCaseClause
Inherits BoundSingleValueCaseClause
Public Sub New(syntax As SyntaxNode, operatorKind As BinaryOperatorKind, valueOpt As BoundExpression, conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RelationalCaseClause, syntax, valueOpt, conditionOpt, hasErrors OrElse valueOpt.NonNullAndHasErrors() OrElse conditionOpt.NonNullAndHasErrors())
Me._OperatorKind = operatorKind
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As BinaryOperatorKind
Public ReadOnly Property OperatorKind As BinaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRelationalCaseClause(Me)
End Function
Public Function Update(operatorKind As BinaryOperatorKind, valueOpt As BoundExpression, conditionOpt As BoundExpression) As BoundRelationalCaseClause
If operatorKind <> Me.OperatorKind OrElse valueOpt IsNot Me.ValueOpt OrElse conditionOpt IsNot Me.ConditionOpt Then
Dim result = New BoundRelationalCaseClause(Me.Syntax, operatorKind, valueOpt, conditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundLoopStatement
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, continueLabel As LabelSymbol, exitLabel As LabelSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ContinueLabel = continueLabel
Me._ExitLabel = exitLabel
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, continueLabel As LabelSymbol, exitLabel As LabelSymbol)
MyBase.New(kind, syntax)
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ContinueLabel = continueLabel
Me._ExitLabel = exitLabel
End Sub
Private ReadOnly _ContinueLabel As LabelSymbol
Public ReadOnly Property ContinueLabel As LabelSymbol
Get
Return _ContinueLabel
End Get
End Property
Private ReadOnly _ExitLabel As LabelSymbol
Public ReadOnly Property ExitLabel As LabelSymbol
Get
Return _ExitLabel
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundDoLoopStatement
Inherits BoundLoopStatement
Public Sub New(syntax As SyntaxNode, topConditionOpt As BoundExpression, bottomConditionOpt As BoundExpression, topConditionIsUntil As Boolean, bottomConditionIsUntil As Boolean, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DoLoopStatement, syntax, continueLabel, exitLabel, hasErrors OrElse topConditionOpt.NonNullAndHasErrors() OrElse bottomConditionOpt.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TopConditionOpt = topConditionOpt
Me._BottomConditionOpt = bottomConditionOpt
Me._TopConditionIsUntil = topConditionIsUntil
Me._BottomConditionIsUntil = bottomConditionIsUntil
Me._Body = body
End Sub
Private ReadOnly _TopConditionOpt As BoundExpression
Public ReadOnly Property TopConditionOpt As BoundExpression
Get
Return _TopConditionOpt
End Get
End Property
Private ReadOnly _BottomConditionOpt As BoundExpression
Public ReadOnly Property BottomConditionOpt As BoundExpression
Get
Return _BottomConditionOpt
End Get
End Property
Private ReadOnly _TopConditionIsUntil As Boolean
Public ReadOnly Property TopConditionIsUntil As Boolean
Get
Return _TopConditionIsUntil
End Get
End Property
Private ReadOnly _BottomConditionIsUntil As Boolean
Public ReadOnly Property BottomConditionIsUntil As Boolean
Get
Return _BottomConditionIsUntil
End Get
End Property
Private ReadOnly _Body As BoundStatement
Public ReadOnly Property Body As BoundStatement
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDoLoopStatement(Me)
End Function
Public Function Update(topConditionOpt As BoundExpression, bottomConditionOpt As BoundExpression, topConditionIsUntil As Boolean, bottomConditionIsUntil As Boolean, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundDoLoopStatement
If topConditionOpt IsNot Me.TopConditionOpt OrElse bottomConditionOpt IsNot Me.BottomConditionOpt OrElse topConditionIsUntil <> Me.TopConditionIsUntil OrElse bottomConditionIsUntil <> Me.BottomConditionIsUntil OrElse body IsNot Me.Body OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundDoLoopStatement(Me.Syntax, topConditionOpt, bottomConditionOpt, topConditionIsUntil, bottomConditionIsUntil, body, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundWhileStatement
Inherits BoundLoopStatement
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.WhileStatement, syntax, continueLabel, exitLabel, hasErrors OrElse condition.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._Body = body
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _Body As BoundStatement
Public ReadOnly Property Body As BoundStatement
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWhileStatement(Me)
End Function
Public Function Update(condition As BoundExpression, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundWhileStatement
If condition IsNot Me.Condition OrElse body IsNot Me.Body OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundWhileStatement(Me.Syntax, condition, body, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundForStatement
Inherits BoundLoopStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, continueLabel, exitLabel, hasErrors)
Debug.Assert(controlVariable IsNot Nothing, "Field 'controlVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._DeclaredOrInferredLocalOpt = declaredOrInferredLocalOpt
Me._ControlVariable = controlVariable
Me._Body = body
Me._NextVariablesOpt = nextVariablesOpt
End Sub
Private ReadOnly _DeclaredOrInferredLocalOpt As LocalSymbol
Public ReadOnly Property DeclaredOrInferredLocalOpt As LocalSymbol
Get
Return _DeclaredOrInferredLocalOpt
End Get
End Property
Private ReadOnly _ControlVariable As BoundExpression
Public ReadOnly Property ControlVariable As BoundExpression
Get
Return _ControlVariable
End Get
End Property
Private ReadOnly _Body As BoundStatement
Public ReadOnly Property Body As BoundStatement
Get
Return _Body
End Get
End Property
Private ReadOnly _NextVariablesOpt As ImmutableArray(Of BoundExpression)
Public ReadOnly Property NextVariablesOpt As ImmutableArray(Of BoundExpression)
Get
Return _NextVariablesOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundForToUserDefinedOperators
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, leftOperandPlaceholder As BoundRValuePlaceholder, rightOperandPlaceholder As BoundRValuePlaceholder, addition As BoundUserDefinedBinaryOperator, subtraction As BoundUserDefinedBinaryOperator, lessThanOrEqual As BoundExpression, greaterThanOrEqual As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ForToUserDefinedOperators, syntax, hasErrors OrElse leftOperandPlaceholder.NonNullAndHasErrors() OrElse rightOperandPlaceholder.NonNullAndHasErrors() OrElse addition.NonNullAndHasErrors() OrElse subtraction.NonNullAndHasErrors() OrElse lessThanOrEqual.NonNullAndHasErrors() OrElse greaterThanOrEqual.NonNullAndHasErrors())
Debug.Assert(leftOperandPlaceholder IsNot Nothing, "Field 'leftOperandPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(rightOperandPlaceholder IsNot Nothing, "Field 'rightOperandPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(addition IsNot Nothing, "Field 'addition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(subtraction IsNot Nothing, "Field 'subtraction' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(lessThanOrEqual IsNot Nothing, "Field 'lessThanOrEqual' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(greaterThanOrEqual IsNot Nothing, "Field 'greaterThanOrEqual' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LeftOperandPlaceholder = leftOperandPlaceholder
Me._RightOperandPlaceholder = rightOperandPlaceholder
Me._Addition = addition
Me._Subtraction = subtraction
Me._LessThanOrEqual = lessThanOrEqual
Me._GreaterThanOrEqual = greaterThanOrEqual
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LeftOperandPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property LeftOperandPlaceholder As BoundRValuePlaceholder
Get
Return _LeftOperandPlaceholder
End Get
End Property
Private ReadOnly _RightOperandPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property RightOperandPlaceholder As BoundRValuePlaceholder
Get
Return _RightOperandPlaceholder
End Get
End Property
Private ReadOnly _Addition As BoundUserDefinedBinaryOperator
Public ReadOnly Property Addition As BoundUserDefinedBinaryOperator
Get
Return _Addition
End Get
End Property
Private ReadOnly _Subtraction As BoundUserDefinedBinaryOperator
Public ReadOnly Property Subtraction As BoundUserDefinedBinaryOperator
Get
Return _Subtraction
End Get
End Property
Private ReadOnly _LessThanOrEqual As BoundExpression
Public ReadOnly Property LessThanOrEqual As BoundExpression
Get
Return _LessThanOrEqual
End Get
End Property
Private ReadOnly _GreaterThanOrEqual As BoundExpression
Public ReadOnly Property GreaterThanOrEqual As BoundExpression
Get
Return _GreaterThanOrEqual
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitForToUserDefinedOperators(Me)
End Function
Public Function Update(leftOperandPlaceholder As BoundRValuePlaceholder, rightOperandPlaceholder As BoundRValuePlaceholder, addition As BoundUserDefinedBinaryOperator, subtraction As BoundUserDefinedBinaryOperator, lessThanOrEqual As BoundExpression, greaterThanOrEqual As BoundExpression) As BoundForToUserDefinedOperators
If leftOperandPlaceholder IsNot Me.LeftOperandPlaceholder OrElse rightOperandPlaceholder IsNot Me.RightOperandPlaceholder OrElse addition IsNot Me.Addition OrElse subtraction IsNot Me.Subtraction OrElse lessThanOrEqual IsNot Me.LessThanOrEqual OrElse greaterThanOrEqual IsNot Me.GreaterThanOrEqual Then
Dim result = New BoundForToUserDefinedOperators(Me.Syntax, leftOperandPlaceholder, rightOperandPlaceholder, addition, subtraction, lessThanOrEqual, greaterThanOrEqual, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundForToStatement
Inherits BoundForStatement
Public Sub New(syntax As SyntaxNode, initialValue As BoundExpression, limitValue As BoundExpression, stepValue As BoundExpression, checked As Boolean, operatorsOpt As BoundForToUserDefinedOperators, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ForToStatement, syntax, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, hasErrors OrElse initialValue.NonNullAndHasErrors() OrElse limitValue.NonNullAndHasErrors() OrElse stepValue.NonNullAndHasErrors() OrElse operatorsOpt.NonNullAndHasErrors() OrElse controlVariable.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors() OrElse nextVariablesOpt.NonNullAndHasErrors())
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(limitValue IsNot Nothing, "Field 'limitValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(stepValue IsNot Nothing, "Field 'stepValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(controlVariable IsNot Nothing, "Field 'controlVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitialValue = initialValue
Me._LimitValue = limitValue
Me._StepValue = stepValue
Me._Checked = checked
Me._OperatorsOpt = operatorsOpt
End Sub
Private ReadOnly _InitialValue As BoundExpression
Public ReadOnly Property InitialValue As BoundExpression
Get
Return _InitialValue
End Get
End Property
Private ReadOnly _LimitValue As BoundExpression
Public ReadOnly Property LimitValue As BoundExpression
Get
Return _LimitValue
End Get
End Property
Private ReadOnly _StepValue As BoundExpression
Public ReadOnly Property StepValue As BoundExpression
Get
Return _StepValue
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _OperatorsOpt As BoundForToUserDefinedOperators
Public ReadOnly Property OperatorsOpt As BoundForToUserDefinedOperators
Get
Return _OperatorsOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitForToStatement(Me)
End Function
Public Function Update(initialValue As BoundExpression, limitValue As BoundExpression, stepValue As BoundExpression, checked As Boolean, operatorsOpt As BoundForToUserDefinedOperators, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundForToStatement
If initialValue IsNot Me.InitialValue OrElse limitValue IsNot Me.LimitValue OrElse stepValue IsNot Me.StepValue OrElse checked <> Me.Checked OrElse operatorsOpt IsNot Me.OperatorsOpt OrElse declaredOrInferredLocalOpt IsNot Me.DeclaredOrInferredLocalOpt OrElse controlVariable IsNot Me.ControlVariable OrElse body IsNot Me.Body OrElse nextVariablesOpt <> Me.NextVariablesOpt OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundForToStatement(Me.Syntax, initialValue, limitValue, stepValue, checked, operatorsOpt, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundForEachStatement
Inherits BoundForStatement
Public Sub New(syntax As SyntaxNode, collection As BoundExpression, enumeratorInfo As ForEachEnumeratorInfo, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ForEachStatement, syntax, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, hasErrors OrElse collection.NonNullAndHasErrors() OrElse controlVariable.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors() OrElse nextVariablesOpt.NonNullAndHasErrors())
Debug.Assert(collection IsNot Nothing, "Field 'collection' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(enumeratorInfo IsNot Nothing, "Field 'enumeratorInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(controlVariable IsNot Nothing, "Field 'controlVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Collection = collection
Me._EnumeratorInfo = enumeratorInfo
End Sub
Private ReadOnly _Collection As BoundExpression
Public ReadOnly Property Collection As BoundExpression
Get
Return _Collection
End Get
End Property
Private ReadOnly _EnumeratorInfo As ForEachEnumeratorInfo
Public ReadOnly Property EnumeratorInfo As ForEachEnumeratorInfo
Get
Return _EnumeratorInfo
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitForEachStatement(Me)
End Function
Public Function Update(collection As BoundExpression, enumeratorInfo As ForEachEnumeratorInfo, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundForEachStatement
If collection IsNot Me.Collection OrElse enumeratorInfo IsNot Me.EnumeratorInfo OrElse declaredOrInferredLocalOpt IsNot Me.DeclaredOrInferredLocalOpt OrElse controlVariable IsNot Me.ControlVariable OrElse body IsNot Me.Body OrElse nextVariablesOpt <> Me.NextVariablesOpt OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundForEachStatement(Me.Syntax, collection, enumeratorInfo, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundExitStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ExitStatement, syntax, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol)
MyBase.New(BoundKind.ExitStatement, syntax)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitExitStatement(Me)
End Function
Public Function Update(label As LabelSymbol) As BoundExitStatement
If label IsNot Me.Label Then
Dim result = New BoundExitStatement(Me.Syntax, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundContinueStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ContinueStatement, syntax, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol)
MyBase.New(BoundKind.ContinueStatement, syntax)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitContinueStatement(Me)
End Function
Public Function Update(label As LabelSymbol) As BoundContinueStatement
If label IsNot Me.Label Then
Dim result = New BoundContinueStatement(Me.Syntax, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTryStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, tryBlock As BoundBlock, catchBlocks As ImmutableArray(Of BoundCatchBlock), finallyBlockOpt As BoundBlock, exitLabelOpt As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TryStatement, syntax, hasErrors OrElse tryBlock.NonNullAndHasErrors() OrElse catchBlocks.NonNullAndHasErrors() OrElse finallyBlockOpt.NonNullAndHasErrors())
Debug.Assert(tryBlock IsNot Nothing, "Field 'tryBlock' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (catchBlocks.IsDefault), "Field 'catchBlocks' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TryBlock = tryBlock
Me._CatchBlocks = catchBlocks
Me._FinallyBlockOpt = finallyBlockOpt
Me._ExitLabelOpt = exitLabelOpt
End Sub
Private ReadOnly _TryBlock As BoundBlock
Public ReadOnly Property TryBlock As BoundBlock
Get
Return _TryBlock
End Get
End Property
Private ReadOnly _CatchBlocks As ImmutableArray(Of BoundCatchBlock)
Public ReadOnly Property CatchBlocks As ImmutableArray(Of BoundCatchBlock)
Get
Return _CatchBlocks
End Get
End Property
Private ReadOnly _FinallyBlockOpt As BoundBlock
Public ReadOnly Property FinallyBlockOpt As BoundBlock
Get
Return _FinallyBlockOpt
End Get
End Property
Private ReadOnly _ExitLabelOpt As LabelSymbol
Public ReadOnly Property ExitLabelOpt As LabelSymbol
Get
Return _ExitLabelOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTryStatement(Me)
End Function
Public Function Update(tryBlock As BoundBlock, catchBlocks As ImmutableArray(Of BoundCatchBlock), finallyBlockOpt As BoundBlock, exitLabelOpt As LabelSymbol) As BoundTryStatement
If tryBlock IsNot Me.TryBlock OrElse catchBlocks <> Me.CatchBlocks OrElse finallyBlockOpt IsNot Me.FinallyBlockOpt OrElse exitLabelOpt IsNot Me.ExitLabelOpt Then
Dim result = New BoundTryStatement(Me.Syntax, tryBlock, catchBlocks, finallyBlockOpt, exitLabelOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCatchBlock
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, localOpt As LocalSymbol, exceptionSourceOpt As BoundExpression, errorLineNumberOpt As BoundExpression, exceptionFilterOpt As BoundExpression, body As BoundBlock, isSynthesizedAsyncCatchAll As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CatchBlock, syntax, hasErrors OrElse exceptionSourceOpt.NonNullAndHasErrors() OrElse errorLineNumberOpt.NonNullAndHasErrors() OrElse exceptionFilterOpt.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalOpt = localOpt
Me._ExceptionSourceOpt = exceptionSourceOpt
Me._ErrorLineNumberOpt = errorLineNumberOpt
Me._ExceptionFilterOpt = exceptionFilterOpt
Me._Body = body
Me._IsSynthesizedAsyncCatchAll = isSynthesizedAsyncCatchAll
End Sub
Private ReadOnly _LocalOpt As LocalSymbol
Public ReadOnly Property LocalOpt As LocalSymbol
Get
Return _LocalOpt
End Get
End Property
Private ReadOnly _ExceptionSourceOpt As BoundExpression
Public ReadOnly Property ExceptionSourceOpt As BoundExpression
Get
Return _ExceptionSourceOpt
End Get
End Property
Private ReadOnly _ErrorLineNumberOpt As BoundExpression
Public ReadOnly Property ErrorLineNumberOpt As BoundExpression
Get
Return _ErrorLineNumberOpt
End Get
End Property
Private ReadOnly _ExceptionFilterOpt As BoundExpression
Public ReadOnly Property ExceptionFilterOpt As BoundExpression
Get
Return _ExceptionFilterOpt
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _IsSynthesizedAsyncCatchAll As Boolean
Public ReadOnly Property IsSynthesizedAsyncCatchAll As Boolean
Get
Return _IsSynthesizedAsyncCatchAll
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCatchBlock(Me)
End Function
Public Function Update(localOpt As LocalSymbol, exceptionSourceOpt As BoundExpression, errorLineNumberOpt As BoundExpression, exceptionFilterOpt As BoundExpression, body As BoundBlock, isSynthesizedAsyncCatchAll As Boolean) As BoundCatchBlock
If localOpt IsNot Me.LocalOpt OrElse exceptionSourceOpt IsNot Me.ExceptionSourceOpt OrElse errorLineNumberOpt IsNot Me.ErrorLineNumberOpt OrElse exceptionFilterOpt IsNot Me.ExceptionFilterOpt OrElse body IsNot Me.Body OrElse isSynthesizedAsyncCatchAll <> Me.IsSynthesizedAsyncCatchAll Then
Dim result = New BoundCatchBlock(Me.Syntax, localOpt, exceptionSourceOpt, errorLineNumberOpt, exceptionFilterOpt, body, isSynthesizedAsyncCatchAll, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLiteral
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, value As ConstantValue, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Literal, syntax, type, hasErrors)
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, value As ConstantValue, type As TypeSymbol)
MyBase.New(BoundKind.Literal, syntax, type)
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Validate()
End Sub
Private ReadOnly _Value As ConstantValue
Public ReadOnly Property Value As ConstantValue
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLiteral(Me)
End Function
Public Function Update(value As ConstantValue, type As TypeSymbol) As BoundLiteral
If value IsNot Me.Value OrElse type IsNot Me.Type Then
Dim result = New BoundLiteral(Me.Syntax, value, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMeReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MeReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MeReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMeReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMeReference
If type IsNot Me.Type Then
Dim result = New BoundMeReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundValueTypeMeReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ValueTypeMeReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.ValueTypeMeReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitValueTypeMeReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundValueTypeMeReference
If type IsNot Me.Type Then
Dim result = New BoundValueTypeMeReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMyBaseReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MyBaseReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MyBaseReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMyBaseReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMyBaseReference
If type IsNot Me.Type Then
Dim result = New BoundMyBaseReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMyClassReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MyClassReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MyClassReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMyClassReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMyClassReference
If type IsNot Me.Type Then
Dim result = New BoundMyClassReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPreviousSubmissionReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, sourceType As NamedTypeSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.PreviousSubmissionReference, syntax, type, hasErrors)
Debug.Assert(sourceType IsNot Nothing, "Field 'sourceType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._SourceType = sourceType
End Sub
Public Sub New(syntax As SyntaxNode, sourceType As NamedTypeSymbol, type As TypeSymbol)
MyBase.New(BoundKind.PreviousSubmissionReference, syntax, type)
Debug.Assert(sourceType IsNot Nothing, "Field 'sourceType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._SourceType = sourceType
End Sub
Private ReadOnly _SourceType As NamedTypeSymbol
Public ReadOnly Property SourceType As NamedTypeSymbol
Get
Return _SourceType
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPreviousSubmissionReference(Me)
End Function
Public Function Update(sourceType As NamedTypeSymbol, type As TypeSymbol) As BoundPreviousSubmissionReference
If sourceType IsNot Me.SourceType OrElse type IsNot Me.Type Then
Dim result = New BoundPreviousSubmissionReference(Me.Syntax, sourceType, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundHostObjectMemberReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.HostObjectMemberReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.HostObjectMemberReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitHostObjectMemberReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundHostObjectMemberReference
If type IsNot Me.Type Then
Dim result = New BoundHostObjectMemberReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLocal
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Local, syntax, type, hasErrors)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.Local, syntax, type)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Validate()
End Sub
Private ReadOnly _LocalSymbol As LocalSymbol
Public ReadOnly Property LocalSymbol As LocalSymbol
Get
Return _LocalSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLocal(Me)
End Function
Public Function Update(localSymbol As LocalSymbol, isLValue As Boolean, type As TypeSymbol) As BoundLocal
If localSymbol IsNot Me.LocalSymbol OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundLocal(Me.Syntax, localSymbol, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPseudoVariable
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, emitExpressions As PseudoVariableExpressions, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.PseudoVariable, syntax, type, hasErrors)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(emitExpressions IsNot Nothing, "Field 'emitExpressions' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Me._EmitExpressions = emitExpressions
End Sub
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, emitExpressions As PseudoVariableExpressions, type As TypeSymbol)
MyBase.New(BoundKind.PseudoVariable, syntax, type)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(emitExpressions IsNot Nothing, "Field 'emitExpressions' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Me._EmitExpressions = emitExpressions
End Sub
Private ReadOnly _LocalSymbol As LocalSymbol
Public ReadOnly Property LocalSymbol As LocalSymbol
Get
Return _LocalSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _EmitExpressions As PseudoVariableExpressions
Public ReadOnly Property EmitExpressions As PseudoVariableExpressions
Get
Return _EmitExpressions
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPseudoVariable(Me)
End Function
Public Function Update(localSymbol As LocalSymbol, isLValue As Boolean, emitExpressions As PseudoVariableExpressions, type As TypeSymbol) As BoundPseudoVariable
If localSymbol IsNot Me.LocalSymbol OrElse isLValue <> Me.IsLValue OrElse emitExpressions IsNot Me.EmitExpressions OrElse type IsNot Me.Type Then
Dim result = New BoundPseudoVariable(Me.Syntax, localSymbol, isLValue, emitExpressions, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundParameter
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Parameter, syntax, type, hasErrors)
Debug.Assert(parameterSymbol IsNot Nothing, "Field 'parameterSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ParameterSymbol = parameterSymbol
Me._IsLValue = isLValue
Me._SuppressVirtualCalls = suppressVirtualCalls
End Sub
Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.Parameter, syntax, type)
Debug.Assert(parameterSymbol IsNot Nothing, "Field 'parameterSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ParameterSymbol = parameterSymbol
Me._IsLValue = isLValue
Me._SuppressVirtualCalls = suppressVirtualCalls
End Sub
Private ReadOnly _ParameterSymbol As ParameterSymbol
Public ReadOnly Property ParameterSymbol As ParameterSymbol
Get
Return _ParameterSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _SuppressVirtualCalls As Boolean
Public Overrides ReadOnly Property SuppressVirtualCalls As Boolean
Get
Return _SuppressVirtualCalls
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitParameter(Me)
End Function
Public Function Update(parameterSymbol As ParameterSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, type As TypeSymbol) As BoundParameter
If parameterSymbol IsNot Me.ParameterSymbol OrElse isLValue <> Me.IsLValue OrElse suppressVirtualCalls <> Me.SuppressVirtualCalls OrElse type IsNot Me.Type Then
Dim result = New BoundParameter(Me.Syntax, parameterSymbol, isLValue, suppressVirtualCalls, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundByRefArgumentPlaceholder
Inherits BoundValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, isOut As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ByRefArgumentPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsOut = isOut
End Sub
Public Sub New(syntax As SyntaxNode, isOut As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.ByRefArgumentPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsOut = isOut
End Sub
Private ReadOnly _IsOut As Boolean
Public ReadOnly Property IsOut As Boolean
Get
Return _IsOut
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitByRefArgumentPlaceholder(Me)
End Function
Public Function Update(isOut As Boolean, type As TypeSymbol) As BoundByRefArgumentPlaceholder
If isOut <> Me.IsOut OrElse type IsNot Me.Type Then
Dim result = New BoundByRefArgumentPlaceholder(Me.Syntax, isOut, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundByRefArgumentWithCopyBack
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, originalArgument As BoundExpression, inConversion As BoundExpression, inPlaceholder As BoundByRefArgumentPlaceholder, outConversion As BoundExpression, outPlaceholder As BoundRValuePlaceholder, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ByRefArgumentWithCopyBack, syntax, type, hasErrors OrElse originalArgument.NonNullAndHasErrors() OrElse inConversion.NonNullAndHasErrors() OrElse inPlaceholder.NonNullAndHasErrors() OrElse outConversion.NonNullAndHasErrors() OrElse outPlaceholder.NonNullAndHasErrors())
Debug.Assert(originalArgument IsNot Nothing, "Field 'originalArgument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(inConversion IsNot Nothing, "Field 'inConversion' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(inPlaceholder IsNot Nothing, "Field 'inPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(outConversion IsNot Nothing, "Field 'outConversion' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(outPlaceholder IsNot Nothing, "Field 'outPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OriginalArgument = originalArgument
Me._InConversion = inConversion
Me._InPlaceholder = inPlaceholder
Me._OutConversion = outConversion
Me._OutPlaceholder = outPlaceholder
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OriginalArgument As BoundExpression
Public ReadOnly Property OriginalArgument As BoundExpression
Get
Return _OriginalArgument
End Get
End Property
Private ReadOnly _InConversion As BoundExpression
Public ReadOnly Property InConversion As BoundExpression
Get
Return _InConversion
End Get
End Property
Private ReadOnly _InPlaceholder As BoundByRefArgumentPlaceholder
Public ReadOnly Property InPlaceholder As BoundByRefArgumentPlaceholder
Get
Return _InPlaceholder
End Get
End Property
Private ReadOnly _OutConversion As BoundExpression
Public ReadOnly Property OutConversion As BoundExpression
Get
Return _OutConversion
End Get
End Property
Private ReadOnly _OutPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property OutPlaceholder As BoundRValuePlaceholder
Get
Return _OutPlaceholder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitByRefArgumentWithCopyBack(Me)
End Function
Public Function Update(originalArgument As BoundExpression, inConversion As BoundExpression, inPlaceholder As BoundByRefArgumentPlaceholder, outConversion As BoundExpression, outPlaceholder As BoundRValuePlaceholder, type As TypeSymbol) As BoundByRefArgumentWithCopyBack
If originalArgument IsNot Me.OriginalArgument OrElse inConversion IsNot Me.InConversion OrElse inPlaceholder IsNot Me.InPlaceholder OrElse outConversion IsNot Me.OutConversion OrElse outPlaceholder IsNot Me.OutPlaceholder OrElse type IsNot Me.Type Then
Dim result = New BoundByRefArgumentWithCopyBack(Me.Syntax, originalArgument, inConversion, inPlaceholder, outConversion, outPlaceholder, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateBoundArgumentSupportingAssignmentWithCapture
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, originalArgument As BoundExpression, localSymbol As SynthesizedLocal, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateBoundArgumentSupportingAssignmentWithCapture, syntax, type, hasErrors OrElse originalArgument.NonNullAndHasErrors())
Debug.Assert(originalArgument IsNot Nothing, "Field 'originalArgument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OriginalArgument = originalArgument
Me._LocalSymbol = localSymbol
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OriginalArgument As BoundExpression
Public ReadOnly Property OriginalArgument As BoundExpression
Get
Return _OriginalArgument
End Get
End Property
Private ReadOnly _LocalSymbol As SynthesizedLocal
Public ReadOnly Property LocalSymbol As SynthesizedLocal
Get
Return _LocalSymbol
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateBoundArgumentSupportingAssignmentWithCapture(Me)
End Function
Public Function Update(originalArgument As BoundExpression, localSymbol As SynthesizedLocal, type As TypeSymbol) As BoundLateBoundArgumentSupportingAssignmentWithCapture
If originalArgument IsNot Me.OriginalArgument OrElse localSymbol IsNot Me.LocalSymbol OrElse type IsNot Me.Type Then
Dim result = New BoundLateBoundArgumentSupportingAssignmentWithCapture(Me.Syntax, originalArgument, localSymbol, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLabelStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.LabelStatement, syntax, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol)
MyBase.New(BoundKind.LabelStatement, syntax)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLabelStatement(Me)
End Function
Public Function Update(label As LabelSymbol) As BoundLabelStatement
If label IsNot Me.Label Then
Dim result = New BoundLabelStatement(Me.Syntax, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLabel
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Label, syntax, type, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, type As TypeSymbol)
MyBase.New(BoundKind.Label, syntax, type)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLabel(Me)
End Function
Public Function Update(label As LabelSymbol, type As TypeSymbol) As BoundLabel
If label IsNot Me.Label OrElse type IsNot Me.Type Then
Dim result = New BoundLabel(Me.Syntax, label, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGotoStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, labelExpressionOpt As BoundLabel, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GotoStatement, syntax, hasErrors OrElse labelExpressionOpt.NonNullAndHasErrors())
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
Me._LabelExpressionOpt = labelExpressionOpt
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
Private ReadOnly _LabelExpressionOpt As BoundLabel
Public ReadOnly Property LabelExpressionOpt As BoundLabel
Get
Return _LabelExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGotoStatement(Me)
End Function
Public Function Update(label As LabelSymbol, labelExpressionOpt As BoundLabel) As BoundGotoStatement
If label IsNot Me.Label OrElse labelExpressionOpt IsNot Me.LabelExpressionOpt Then
Dim result = New BoundGotoStatement(Me.Syntax, label, labelExpressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundStatementList
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statements As ImmutableArray(Of BoundStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.StatementList, syntax, hasErrors OrElse statements.NonNullAndHasErrors())
Debug.Assert(Not (statements.IsDefault), "Field 'statements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Statements = statements
End Sub
Private ReadOnly _Statements As ImmutableArray(Of BoundStatement)
Public ReadOnly Property Statements As ImmutableArray(Of BoundStatement)
Get
Return _Statements
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitStatementList(Me)
End Function
Public Function Update(statements As ImmutableArray(Of BoundStatement)) As BoundStatementList
If statements <> Me.Statements Then
Dim result = New BoundStatementList(Me.Syntax, statements, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConditionalGoto
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, jumpIfTrue As Boolean, label As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConditionalGoto, syntax, hasErrors OrElse condition.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._JumpIfTrue = jumpIfTrue
Me._Label = label
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _JumpIfTrue As Boolean
Public ReadOnly Property JumpIfTrue As Boolean
Get
Return _JumpIfTrue
End Get
End Property
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConditionalGoto(Me)
End Function
Public Function Update(condition As BoundExpression, jumpIfTrue As Boolean, label As LabelSymbol) As BoundConditionalGoto
If condition IsNot Me.Condition OrElse jumpIfTrue <> Me.JumpIfTrue OrElse label IsNot Me.Label Then
Dim result = New BoundConditionalGoto(Me.Syntax, condition, jumpIfTrue, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundWithStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, originalExpression As BoundExpression, body As BoundBlock, binder As WithBlockBinder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.WithStatement, syntax, hasErrors OrElse originalExpression.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(originalExpression IsNot Nothing, "Field 'originalExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OriginalExpression = originalExpression
Me._Body = body
Me._Binder = binder
End Sub
Private ReadOnly _OriginalExpression As BoundExpression
Public ReadOnly Property OriginalExpression As BoundExpression
Get
Return _OriginalExpression
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _Binder As WithBlockBinder
Public ReadOnly Property Binder As WithBlockBinder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWithStatement(Me)
End Function
Public Function Update(originalExpression As BoundExpression, body As BoundBlock, binder As WithBlockBinder) As BoundWithStatement
If originalExpression IsNot Me.OriginalExpression OrElse body IsNot Me.Body OrElse binder IsNot Me.Binder Then
Dim result = New BoundWithStatement(Me.Syntax, originalExpression, body, binder, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class UnboundLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, flags As SourceMemberFlags, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol, bindingCache As UnboundLambda.UnboundLambdaBindingCache, hasErrors As Boolean)
MyBase.New(BoundKind.UnboundLambda, syntax, Nothing, hasErrors)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(bindingCache IsNot Nothing, "Field 'bindingCache' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Flags = flags
Me._Parameters = parameters
Me._ReturnType = returnType
Me._BindingCache = bindingCache
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, binder As Binder, flags As SourceMemberFlags, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol, bindingCache As UnboundLambda.UnboundLambdaBindingCache)
MyBase.New(BoundKind.UnboundLambda, syntax, Nothing)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(bindingCache IsNot Nothing, "Field 'bindingCache' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Flags = flags
Me._Parameters = parameters
Me._ReturnType = returnType
Me._BindingCache = bindingCache
Validate()
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _Flags As SourceMemberFlags
Public ReadOnly Property Flags As SourceMemberFlags
Get
Return _Flags
End Get
End Property
Private ReadOnly _Parameters As ImmutableArray(Of ParameterSymbol)
Public ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _Parameters
End Get
End Property
Private ReadOnly _ReturnType As TypeSymbol
Public ReadOnly Property ReturnType As TypeSymbol
Get
Return _ReturnType
End Get
End Property
Private ReadOnly _BindingCache As UnboundLambda.UnboundLambdaBindingCache
Public ReadOnly Property BindingCache As UnboundLambda.UnboundLambdaBindingCache
Get
Return _BindingCache
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnboundLambda(Me)
End Function
Public Function Update(binder As Binder, flags As SourceMemberFlags, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol, bindingCache As UnboundLambda.UnboundLambdaBindingCache) As UnboundLambda
If binder IsNot Me.Binder OrElse flags <> Me.Flags OrElse parameters <> Me.Parameters OrElse returnType IsNot Me.ReturnType OrElse bindingCache IsNot Me.BindingCache Then
Dim result = New UnboundLambda(Me.Syntax, binder, flags, parameters, returnType, bindingCache, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, lambdaSymbol As LambdaSymbol, body As BoundBlock, diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol), lambdaBinderOpt As LambdaBodyBinder, delegateRelaxation As ConversionKind, methodConversionKind As MethodConversionKind, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Lambda, syntax, Nothing, hasErrors OrElse body.NonNullAndHasErrors())
Debug.Assert(lambdaSymbol IsNot Nothing, "Field 'lambdaSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LambdaSymbol = lambdaSymbol
Me._Body = body
Me._Diagnostics = diagnostics
Me._LambdaBinderOpt = lambdaBinderOpt
Me._DelegateRelaxation = delegateRelaxation
Me._MethodConversionKind = methodConversionKind
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LambdaSymbol As LambdaSymbol
Public ReadOnly Property LambdaSymbol As LambdaSymbol
Get
Return _LambdaSymbol
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Public ReadOnly Property Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Get
Return _Diagnostics
End Get
End Property
Private ReadOnly _LambdaBinderOpt As LambdaBodyBinder
Public ReadOnly Property LambdaBinderOpt As LambdaBodyBinder
Get
Return _LambdaBinderOpt
End Get
End Property
Private ReadOnly _DelegateRelaxation As ConversionKind
Public ReadOnly Property DelegateRelaxation As ConversionKind
Get
Return _DelegateRelaxation
End Get
End Property
Private ReadOnly _MethodConversionKind As MethodConversionKind
Public ReadOnly Property MethodConversionKind As MethodConversionKind
Get
Return _MethodConversionKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLambda(Me)
End Function
Public Function Update(lambdaSymbol As LambdaSymbol, body As BoundBlock, diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol), lambdaBinderOpt As LambdaBodyBinder, delegateRelaxation As ConversionKind, methodConversionKind As MethodConversionKind) As BoundLambda
If lambdaSymbol IsNot Me.LambdaSymbol OrElse body IsNot Me.Body OrElse diagnostics <> Me.Diagnostics OrElse lambdaBinderOpt IsNot Me.LambdaBinderOpt OrElse delegateRelaxation <> Me.DelegateRelaxation OrElse methodConversionKind <> Me.MethodConversionKind Then
Dim result = New BoundLambda(Me.Syntax, lambdaSymbol, body, diagnostics, lambdaBinderOpt, delegateRelaxation, methodConversionKind, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundQueryExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, lastOperator As BoundQueryClauseBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryExpression, syntax, type, hasErrors OrElse lastOperator.NonNullAndHasErrors())
Debug.Assert(lastOperator IsNot Nothing, "Field 'lastOperator' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LastOperator = lastOperator
End Sub
Private ReadOnly _LastOperator As BoundQueryClauseBase
Public ReadOnly Property LastOperator As BoundQueryClauseBase
Get
Return _LastOperator
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryExpression(Me)
End Function
Public Function Update(lastOperator As BoundQueryClauseBase, type As TypeSymbol) As BoundQueryExpression
If lastOperator IsNot Me.LastOperator OrElse type IsNot Me.Type Then
Dim result = New BoundQueryExpression(Me.Syntax, lastOperator, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundQueryPart
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundQuerySource
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QuerySource, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQuerySource(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundQuerySource
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundQuerySource(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundToQueryableCollectionConversion
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, conversionCall As BoundCall, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ToQueryableCollectionConversion, syntax, type, hasErrors OrElse conversionCall.NonNullAndHasErrors())
Debug.Assert(conversionCall IsNot Nothing, "Field 'conversionCall' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ConversionCall = conversionCall
End Sub
Private ReadOnly _ConversionCall As BoundCall
Public ReadOnly Property ConversionCall As BoundCall
Get
Return _ConversionCall
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitToQueryableCollectionConversion(Me)
End Function
Public Function Update(conversionCall As BoundCall, type As TypeSymbol) As BoundToQueryableCollectionConversion
If conversionCall IsNot Me.ConversionCall OrElse type IsNot Me.Type Then
Dim result = New BoundToQueryableCollectionConversion(Me.Syntax, conversionCall, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundQueryClauseBase
Inherits BoundQueryPart
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariables = rangeVariables
Me._CompoundVariableType = compoundVariableType
Me._Binders = binders
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariables = rangeVariables
Me._CompoundVariableType = compoundVariableType
Me._Binders = binders
End Sub
Private ReadOnly _RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Public ReadOnly Property RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Get
Return _RangeVariables
End Get
End Property
Private ReadOnly _CompoundVariableType As TypeSymbol
Public ReadOnly Property CompoundVariableType As TypeSymbol
Get
Return _CompoundVariableType
End Get
End Property
Private ReadOnly _Binders As ImmutableArray(Of Binder)
Public ReadOnly Property Binders As ImmutableArray(Of Binder)
Get
Return _Binders
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundQueryableSource
Inherits BoundQueryClauseBase
Public Sub New(syntax As SyntaxNode, source As BoundQueryPart, rangeVariableOpt As RangeVariableSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryableSource, syntax, rangeVariables, compoundVariableType, binders, type, hasErrors OrElse source.NonNullAndHasErrors())
Debug.Assert(source IsNot Nothing, "Field 'source' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Source = source
Me._RangeVariableOpt = rangeVariableOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Source As BoundQueryPart
Public ReadOnly Property Source As BoundQueryPart
Get
Return _Source
End Get
End Property
Private ReadOnly _RangeVariableOpt As RangeVariableSymbol
Public ReadOnly Property RangeVariableOpt As RangeVariableSymbol
Get
Return _RangeVariableOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryableSource(Me)
End Function
Public Function Update(source As BoundQueryPart, rangeVariableOpt As RangeVariableSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol) As BoundQueryableSource
If source IsNot Me.Source OrElse rangeVariableOpt IsNot Me.RangeVariableOpt OrElse rangeVariables <> Me.RangeVariables OrElse compoundVariableType IsNot Me.CompoundVariableType OrElse binders <> Me.Binders OrElse type IsNot Me.Type Then
Dim result = New BoundQueryableSource(Me.Syntax, source, rangeVariableOpt, rangeVariables, compoundVariableType, binders, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundQueryClause
Inherits BoundQueryClauseBase
Public Sub New(syntax As SyntaxNode, underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryClause, syntax, rangeVariables, compoundVariableType, binders, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingExpression = underlyingExpression
End Sub
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryClause(Me)
End Function
Public Function Update(underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol) As BoundQueryClause
If underlyingExpression IsNot Me.UnderlyingExpression OrElse rangeVariables <> Me.RangeVariables OrElse compoundVariableType IsNot Me.CompoundVariableType OrElse binders <> Me.Binders OrElse type IsNot Me.Type Then
Dim result = New BoundQueryClause(Me.Syntax, underlyingExpression, rangeVariables, compoundVariableType, binders, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundOrdering
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, underlyingExpression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Ordering, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingExpression = underlyingExpression
End Sub
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitOrdering(Me)
End Function
Public Function Update(underlyingExpression As BoundExpression, type As TypeSymbol) As BoundOrdering
If underlyingExpression IsNot Me.UnderlyingExpression OrElse type IsNot Me.Type Then
Dim result = New BoundOrdering(Me.Syntax, underlyingExpression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundQueryLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, lambdaSymbol As SynthesizedLambdaSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), expression As BoundExpression, exprIsOperandOfConditionalBranch As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryLambda, syntax, Nothing, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(lambdaSymbol IsNot Nothing, "Field 'lambdaSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LambdaSymbol = lambdaSymbol
Me._RangeVariables = rangeVariables
Me._Expression = expression
Me._ExprIsOperandOfConditionalBranch = exprIsOperandOfConditionalBranch
End Sub
Private ReadOnly _LambdaSymbol As SynthesizedLambdaSymbol
Public ReadOnly Property LambdaSymbol As SynthesizedLambdaSymbol
Get
Return _LambdaSymbol
End Get
End Property
Private ReadOnly _RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Public ReadOnly Property RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Get
Return _RangeVariables
End Get
End Property
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _ExprIsOperandOfConditionalBranch As Boolean
Public ReadOnly Property ExprIsOperandOfConditionalBranch As Boolean
Get
Return _ExprIsOperandOfConditionalBranch
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryLambda(Me)
End Function
Public Function Update(lambdaSymbol As SynthesizedLambdaSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), expression As BoundExpression, exprIsOperandOfConditionalBranch As Boolean) As BoundQueryLambda
If lambdaSymbol IsNot Me.LambdaSymbol OrElse rangeVariables <> Me.RangeVariables OrElse expression IsNot Me.Expression OrElse exprIsOperandOfConditionalBranch <> Me.ExprIsOperandOfConditionalBranch Then
Dim result = New BoundQueryLambda(Me.Syntax, lambdaSymbol, rangeVariables, expression, exprIsOperandOfConditionalBranch, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRangeVariableAssignment
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, rangeVariable As RangeVariableSymbol, value As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RangeVariableAssignment, syntax, type, hasErrors OrElse value.NonNullAndHasErrors())
Debug.Assert(rangeVariable IsNot Nothing, "Field 'rangeVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariable = rangeVariable
Me._Value = value
End Sub
Private ReadOnly _RangeVariable As RangeVariableSymbol
Public ReadOnly Property RangeVariable As RangeVariableSymbol
Get
Return _RangeVariable
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRangeVariableAssignment(Me)
End Function
Public Function Update(rangeVariable As RangeVariableSymbol, value As BoundExpression, type As TypeSymbol) As BoundRangeVariableAssignment
If rangeVariable IsNot Me.RangeVariable OrElse value IsNot Me.Value OrElse type IsNot Me.Type Then
Dim result = New BoundRangeVariableAssignment(Me.Syntax, rangeVariable, value, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class GroupTypeInferenceLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, parameters As ImmutableArray(Of ParameterSymbol), compilation As VisualBasicCompilation, hasErrors As Boolean)
MyBase.New(BoundKind.GroupTypeInferenceLambda, syntax, Nothing, hasErrors)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compilation IsNot Nothing, "Field 'compilation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Parameters = parameters
Me._Compilation = compilation
End Sub
Public Sub New(syntax As SyntaxNode, binder As Binder, parameters As ImmutableArray(Of ParameterSymbol), compilation As VisualBasicCompilation)
MyBase.New(BoundKind.GroupTypeInferenceLambda, syntax, Nothing)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compilation IsNot Nothing, "Field 'compilation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Parameters = parameters
Me._Compilation = compilation
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _Parameters As ImmutableArray(Of ParameterSymbol)
Public ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _Parameters
End Get
End Property
Private ReadOnly _Compilation As VisualBasicCompilation
Public ReadOnly Property Compilation As VisualBasicCompilation
Get
Return _Compilation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGroupTypeInferenceLambda(Me)
End Function
Public Function Update(binder As Binder, parameters As ImmutableArray(Of ParameterSymbol), compilation As VisualBasicCompilation) As GroupTypeInferenceLambda
If binder IsNot Me.Binder OrElse parameters <> Me.Parameters OrElse compilation IsNot Me.Compilation Then
Dim result = New GroupTypeInferenceLambda(Me.Syntax, binder, parameters, compilation, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAggregateClause
Inherits BoundQueryClauseBase
Public Sub New(syntax As SyntaxNode, capturedGroupOpt As BoundQueryClauseBase, groupPlaceholderOpt As BoundRValuePlaceholder, underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AggregateClause, syntax, rangeVariables, compoundVariableType, binders, type, hasErrors OrElse capturedGroupOpt.NonNullAndHasErrors() OrElse groupPlaceholderOpt.NonNullAndHasErrors() OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CapturedGroupOpt = capturedGroupOpt
Me._GroupPlaceholderOpt = groupPlaceholderOpt
Me._UnderlyingExpression = underlyingExpression
End Sub
Private ReadOnly _CapturedGroupOpt As BoundQueryClauseBase
Public ReadOnly Property CapturedGroupOpt As BoundQueryClauseBase
Get
Return _CapturedGroupOpt
End Get
End Property
Private ReadOnly _GroupPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property GroupPlaceholderOpt As BoundRValuePlaceholder
Get
Return _GroupPlaceholderOpt
End Get
End Property
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAggregateClause(Me)
End Function
Public Function Update(capturedGroupOpt As BoundQueryClauseBase, groupPlaceholderOpt As BoundRValuePlaceholder, underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol) As BoundAggregateClause
If capturedGroupOpt IsNot Me.CapturedGroupOpt OrElse groupPlaceholderOpt IsNot Me.GroupPlaceholderOpt OrElse underlyingExpression IsNot Me.UnderlyingExpression OrElse rangeVariables <> Me.RangeVariables OrElse compoundVariableType IsNot Me.CompoundVariableType OrElse binders <> Me.Binders OrElse type IsNot Me.Type Then
Dim result = New BoundAggregateClause(Me.Syntax, capturedGroupOpt, groupPlaceholderOpt, underlyingExpression, rangeVariables, compoundVariableType, binders, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGroupAggregation
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, group As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GroupAggregation, syntax, type, hasErrors OrElse group.NonNullAndHasErrors())
Debug.Assert(group IsNot Nothing, "Field 'group' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Group = group
End Sub
Private ReadOnly _Group As BoundExpression
Public ReadOnly Property Group As BoundExpression
Get
Return _Group
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGroupAggregation(Me)
End Function
Public Function Update(group As BoundExpression, type As TypeSymbol) As BoundGroupAggregation
If group IsNot Me.Group OrElse type IsNot Me.Type Then
Dim result = New BoundGroupAggregation(Me.Syntax, group, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRangeVariable
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, rangeVariable As RangeVariableSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.RangeVariable, syntax, type, hasErrors)
Debug.Assert(rangeVariable IsNot Nothing, "Field 'rangeVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariable = rangeVariable
End Sub
Public Sub New(syntax As SyntaxNode, rangeVariable As RangeVariableSymbol, type As TypeSymbol)
MyBase.New(BoundKind.RangeVariable, syntax, type)
Debug.Assert(rangeVariable IsNot Nothing, "Field 'rangeVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariable = rangeVariable
End Sub
Private ReadOnly _RangeVariable As RangeVariableSymbol
Public ReadOnly Property RangeVariable As RangeVariableSymbol
Get
Return _RangeVariable
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRangeVariable(Me)
End Function
Public Function Update(rangeVariable As RangeVariableSymbol, type As TypeSymbol) As BoundRangeVariable
If rangeVariable IsNot Me.RangeVariable OrElse type IsNot Me.Type Then
Dim result = New BoundRangeVariable(Me.Syntax, rangeVariable, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundAddRemoveHandlerStatement
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, eventAccess As BoundExpression, handler As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, hasErrors)
Debug.Assert(eventAccess IsNot Nothing, "Field 'eventAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(handler IsNot Nothing, "Field 'handler' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._EventAccess = eventAccess
Me._Handler = handler
End Sub
Private ReadOnly _EventAccess As BoundExpression
Public ReadOnly Property EventAccess As BoundExpression
Get
Return _EventAccess
End Get
End Property
Private ReadOnly _Handler As BoundExpression
Public ReadOnly Property Handler As BoundExpression
Get
Return _Handler
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundAddHandlerStatement
Inherits BoundAddRemoveHandlerStatement
Public Sub New(syntax As SyntaxNode, eventAccess As BoundExpression, handler As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AddHandlerStatement, syntax, eventAccess, handler, hasErrors OrElse eventAccess.NonNullAndHasErrors() OrElse handler.NonNullAndHasErrors())
Debug.Assert(eventAccess IsNot Nothing, "Field 'eventAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(handler IsNot Nothing, "Field 'handler' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAddHandlerStatement(Me)
End Function
Public Function Update(eventAccess As BoundExpression, handler As BoundExpression) As BoundAddHandlerStatement
If eventAccess IsNot Me.EventAccess OrElse handler IsNot Me.Handler Then
Dim result = New BoundAddHandlerStatement(Me.Syntax, eventAccess, handler, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRemoveHandlerStatement
Inherits BoundAddRemoveHandlerStatement
Public Sub New(syntax As SyntaxNode, eventAccess As BoundExpression, handler As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RemoveHandlerStatement, syntax, eventAccess, handler, hasErrors OrElse eventAccess.NonNullAndHasErrors() OrElse handler.NonNullAndHasErrors())
Debug.Assert(eventAccess IsNot Nothing, "Field 'eventAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(handler IsNot Nothing, "Field 'handler' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRemoveHandlerStatement(Me)
End Function
Public Function Update(eventAccess As BoundExpression, handler As BoundExpression) As BoundRemoveHandlerStatement
If eventAccess IsNot Me.EventAccess OrElse handler IsNot Me.Handler Then
Dim result = New BoundRemoveHandlerStatement(Me.Syntax, eventAccess, handler, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRaiseEventStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, eventSymbol As EventSymbol, eventInvocation As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RaiseEventStatement, syntax, hasErrors OrElse eventInvocation.NonNullAndHasErrors())
Debug.Assert(eventSymbol IsNot Nothing, "Field 'eventSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(eventInvocation IsNot Nothing, "Field 'eventInvocation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._EventSymbol = eventSymbol
Me._EventInvocation = eventInvocation
End Sub
Private ReadOnly _EventSymbol As EventSymbol
Public ReadOnly Property EventSymbol As EventSymbol
Get
Return _EventSymbol
End Get
End Property
Private ReadOnly _EventInvocation As BoundExpression
Public ReadOnly Property EventInvocation As BoundExpression
Get
Return _EventInvocation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRaiseEventStatement(Me)
End Function
Public Function Update(eventSymbol As EventSymbol, eventInvocation As BoundExpression) As BoundRaiseEventStatement
If eventSymbol IsNot Me.EventSymbol OrElse eventInvocation IsNot Me.EventInvocation Then
Dim result = New BoundRaiseEventStatement(Me.Syntax, eventSymbol, eventInvocation, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUsingStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, resourceList As ImmutableArray(Of BoundLocalDeclarationBase), resourceExpressionOpt As BoundExpression, body As BoundBlock, usingInfo As UsingInfo, locals As ImmutableArray(Of LocalSymbol), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UsingStatement, syntax, hasErrors OrElse resourceList.NonNullAndHasErrors() OrElse resourceExpressionOpt.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(usingInfo IsNot Nothing, "Field 'usingInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ResourceList = resourceList
Me._ResourceExpressionOpt = resourceExpressionOpt
Me._Body = body
Me._UsingInfo = usingInfo
Me._Locals = locals
End Sub
Private ReadOnly _ResourceList As ImmutableArray(Of BoundLocalDeclarationBase)
Public ReadOnly Property ResourceList As ImmutableArray(Of BoundLocalDeclarationBase)
Get
Return _ResourceList
End Get
End Property
Private ReadOnly _ResourceExpressionOpt As BoundExpression
Public ReadOnly Property ResourceExpressionOpt As BoundExpression
Get
Return _ResourceExpressionOpt
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _UsingInfo As UsingInfo
Public ReadOnly Property UsingInfo As UsingInfo
Get
Return _UsingInfo
End Get
End Property
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUsingStatement(Me)
End Function
Public Function Update(resourceList As ImmutableArray(Of BoundLocalDeclarationBase), resourceExpressionOpt As BoundExpression, body As BoundBlock, usingInfo As UsingInfo, locals As ImmutableArray(Of LocalSymbol)) As BoundUsingStatement
If resourceList <> Me.ResourceList OrElse resourceExpressionOpt IsNot Me.ResourceExpressionOpt OrElse body IsNot Me.Body OrElse usingInfo IsNot Me.UsingInfo OrElse locals <> Me.Locals Then
Dim result = New BoundUsingStatement(Me.Syntax, resourceList, resourceExpressionOpt, body, usingInfo, locals, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSyncLockStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, lockExpression As BoundExpression, body As BoundBlock, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SyncLockStatement, syntax, hasErrors OrElse lockExpression.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(lockExpression IsNot Nothing, "Field 'lockExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LockExpression = lockExpression
Me._Body = body
End Sub
Private ReadOnly _LockExpression As BoundExpression
Public ReadOnly Property LockExpression As BoundExpression
Get
Return _LockExpression
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSyncLockStatement(Me)
End Function
Public Function Update(lockExpression As BoundExpression, body As BoundBlock) As BoundSyncLockStatement
If lockExpression IsNot Me.LockExpression OrElse body IsNot Me.Body Then
Dim result = New BoundSyncLockStatement(Me.Syntax, lockExpression, body, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlName
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, xmlNamespace As BoundExpression, localName As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlName, syntax, type, hasErrors OrElse xmlNamespace.NonNullAndHasErrors() OrElse localName.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(xmlNamespace IsNot Nothing, "Field 'xmlNamespace' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(localName IsNot Nothing, "Field 'localName' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._XmlNamespace = xmlNamespace
Me._LocalName = localName
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _XmlNamespace As BoundExpression
Public ReadOnly Property XmlNamespace As BoundExpression
Get
Return _XmlNamespace
End Get
End Property
Private ReadOnly _LocalName As BoundExpression
Public ReadOnly Property LocalName As BoundExpression
Get
Return _LocalName
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlName(Me)
End Function
Public Function Update(xmlNamespace As BoundExpression, localName As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlName
If xmlNamespace IsNot Me.XmlNamespace OrElse localName IsNot Me.LocalName OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlName(Me.Syntax, xmlNamespace, localName, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlNamespace
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, xmlNamespace As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlNamespace, syntax, type, hasErrors OrElse xmlNamespace.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(xmlNamespace IsNot Nothing, "Field 'xmlNamespace' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._XmlNamespace = xmlNamespace
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _XmlNamespace As BoundExpression
Public ReadOnly Property XmlNamespace As BoundExpression
Get
Return _XmlNamespace
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlNamespace(Me)
End Function
Public Function Update(xmlNamespace As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlNamespace
If xmlNamespace IsNot Me.XmlNamespace OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlNamespace(Me.Syntax, xmlNamespace, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlDocument
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, declaration As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlDocument, syntax, type, hasErrors OrElse declaration.NonNullAndHasErrors() OrElse childNodes.NonNullAndHasErrors())
Debug.Assert(declaration IsNot Nothing, "Field 'declaration' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (childNodes.IsDefault), "Field 'childNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(rewriterInfo IsNot Nothing, "Field 'rewriterInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Declaration = declaration
Me._ChildNodes = childNodes
Me._RewriterInfo = rewriterInfo
End Sub
Private ReadOnly _Declaration As BoundExpression
Public ReadOnly Property Declaration As BoundExpression
Get
Return _Declaration
End Get
End Property
Private ReadOnly _ChildNodes As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ChildNodes As ImmutableArray(Of BoundExpression)
Get
Return _ChildNodes
End Get
End Property
Private ReadOnly _RewriterInfo As BoundXmlContainerRewriterInfo
Public ReadOnly Property RewriterInfo As BoundXmlContainerRewriterInfo
Get
Return _RewriterInfo
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlDocument(Me)
End Function
Public Function Update(declaration As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol) As BoundXmlDocument
If declaration IsNot Me.Declaration OrElse childNodes <> Me.ChildNodes OrElse rewriterInfo IsNot Me.RewriterInfo OrElse type IsNot Me.Type Then
Dim result = New BoundXmlDocument(Me.Syntax, declaration, childNodes, rewriterInfo, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlDeclaration
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, version As BoundExpression, encoding As BoundExpression, standalone As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlDeclaration, syntax, type, hasErrors OrElse version.NonNullAndHasErrors() OrElse encoding.NonNullAndHasErrors() OrElse standalone.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Version = version
Me._Encoding = encoding
Me._Standalone = standalone
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Version As BoundExpression
Public ReadOnly Property Version As BoundExpression
Get
Return _Version
End Get
End Property
Private ReadOnly _Encoding As BoundExpression
Public ReadOnly Property Encoding As BoundExpression
Get
Return _Encoding
End Get
End Property
Private ReadOnly _Standalone As BoundExpression
Public ReadOnly Property Standalone As BoundExpression
Get
Return _Standalone
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlDeclaration(Me)
End Function
Public Function Update(version As BoundExpression, encoding As BoundExpression, standalone As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlDeclaration
If version IsNot Me.Version OrElse encoding IsNot Me.Encoding OrElse standalone IsNot Me.Standalone OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlDeclaration(Me.Syntax, version, encoding, standalone, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlProcessingInstruction
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, target As BoundExpression, data As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlProcessingInstruction, syntax, type, hasErrors OrElse target.NonNullAndHasErrors() OrElse data.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(target IsNot Nothing, "Field 'target' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(data IsNot Nothing, "Field 'data' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Target = target
Me._Data = data
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Target As BoundExpression
Public ReadOnly Property Target As BoundExpression
Get
Return _Target
End Get
End Property
Private ReadOnly _Data As BoundExpression
Public ReadOnly Property Data As BoundExpression
Get
Return _Data
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlProcessingInstruction(Me)
End Function
Public Function Update(target As BoundExpression, data As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlProcessingInstruction
If target IsNot Me.Target OrElse data IsNot Me.Data OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlProcessingInstruction(Me.Syntax, target, data, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlComment
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, value As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlComment, syntax, type, hasErrors OrElse value.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlComment(Me)
End Function
Public Function Update(value As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlComment
If value IsNot Me.Value OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlComment(Me.Syntax, value, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlAttribute
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, name As BoundExpression, value As BoundExpression, matchesImport As Boolean, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlAttribute, syntax, type, hasErrors OrElse name.NonNullAndHasErrors() OrElse value.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(name IsNot Nothing, "Field 'name' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Name = name
Me._Value = value
Me._MatchesImport = matchesImport
Me._ObjectCreation = objectCreation
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Name As BoundExpression
Public ReadOnly Property Name As BoundExpression
Get
Return _Name
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
Private ReadOnly _MatchesImport As Boolean
Public ReadOnly Property MatchesImport As Boolean
Get
Return _MatchesImport
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlAttribute(Me)
End Function
Public Function Update(name As BoundExpression, value As BoundExpression, matchesImport As Boolean, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlAttribute
If name IsNot Me.Name OrElse value IsNot Me.Value OrElse matchesImport <> Me.MatchesImport OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlAttribute(Me.Syntax, name, value, matchesImport, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlElement
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, argument As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlElement, syntax, type, hasErrors OrElse argument.NonNullAndHasErrors() OrElse childNodes.NonNullAndHasErrors())
Debug.Assert(argument IsNot Nothing, "Field 'argument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (childNodes.IsDefault), "Field 'childNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(rewriterInfo IsNot Nothing, "Field 'rewriterInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Argument = argument
Me._ChildNodes = childNodes
Me._RewriterInfo = rewriterInfo
End Sub
Private ReadOnly _Argument As BoundExpression
Public ReadOnly Property Argument As BoundExpression
Get
Return _Argument
End Get
End Property
Private ReadOnly _ChildNodes As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ChildNodes As ImmutableArray(Of BoundExpression)
Get
Return _ChildNodes
End Get
End Property
Private ReadOnly _RewriterInfo As BoundXmlContainerRewriterInfo
Public ReadOnly Property RewriterInfo As BoundXmlContainerRewriterInfo
Get
Return _RewriterInfo
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlElement(Me)
End Function
Public Function Update(argument As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol) As BoundXmlElement
If argument IsNot Me.Argument OrElse childNodes <> Me.ChildNodes OrElse rewriterInfo IsNot Me.RewriterInfo OrElse type IsNot Me.Type Then
Dim result = New BoundXmlElement(Me.Syntax, argument, childNodes, rewriterInfo, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlMemberAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, memberAccess As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlMemberAccess, syntax, type, hasErrors OrElse memberAccess.NonNullAndHasErrors())
Debug.Assert(memberAccess IsNot Nothing, "Field 'memberAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._MemberAccess = memberAccess
End Sub
Private ReadOnly _MemberAccess As BoundExpression
Public ReadOnly Property MemberAccess As BoundExpression
Get
Return _MemberAccess
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlMemberAccess(Me)
End Function
Public Function Update(memberAccess As BoundExpression, type As TypeSymbol) As BoundXmlMemberAccess
If memberAccess IsNot Me.MemberAccess OrElse type IsNot Me.Type Then
Dim result = New BoundXmlMemberAccess(Me.Syntax, memberAccess, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlEmbeddedExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlEmbeddedExpression, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlEmbeddedExpression(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundXmlEmbeddedExpression
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundXmlEmbeddedExpression(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlCData
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, value As BoundLiteral, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlCData, syntax, type, hasErrors OrElse value.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Value As BoundLiteral
Public ReadOnly Property Value As BoundLiteral
Get
Return _Value
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlCData(Me)
End Function
Public Function Update(value As BoundLiteral, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlCData
If value IsNot Me.Value OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlCData(Me.Syntax, value, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundResumeStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, resumeKind As ResumeStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ResumeStatement, syntax, hasErrors OrElse labelExpressionOpt.NonNullAndHasErrors())
Me._ResumeKind = resumeKind
Me._LabelOpt = labelOpt
Me._LabelExpressionOpt = labelExpressionOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ResumeKind As ResumeStatementKind
Public ReadOnly Property ResumeKind As ResumeStatementKind
Get
Return _ResumeKind
End Get
End Property
Private ReadOnly _LabelOpt As LabelSymbol
Public ReadOnly Property LabelOpt As LabelSymbol
Get
Return _LabelOpt
End Get
End Property
Private ReadOnly _LabelExpressionOpt As BoundExpression
Public ReadOnly Property LabelExpressionOpt As BoundExpression
Get
Return _LabelExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitResumeStatement(Me)
End Function
Public Function Update(resumeKind As ResumeStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression) As BoundResumeStatement
If resumeKind <> Me.ResumeKind OrElse labelOpt IsNot Me.LabelOpt OrElse labelExpressionOpt IsNot Me.LabelExpressionOpt Then
Dim result = New BoundResumeStatement(Me.Syntax, resumeKind, labelOpt, labelExpressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundOnErrorStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, onErrorKind As OnErrorStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.OnErrorStatement, syntax, hasErrors OrElse labelExpressionOpt.NonNullAndHasErrors())
Me._OnErrorKind = onErrorKind
Me._LabelOpt = labelOpt
Me._LabelExpressionOpt = labelExpressionOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OnErrorKind As OnErrorStatementKind
Public ReadOnly Property OnErrorKind As OnErrorStatementKind
Get
Return _OnErrorKind
End Get
End Property
Private ReadOnly _LabelOpt As LabelSymbol
Public ReadOnly Property LabelOpt As LabelSymbol
Get
Return _LabelOpt
End Get
End Property
Private ReadOnly _LabelExpressionOpt As BoundExpression
Public ReadOnly Property LabelExpressionOpt As BoundExpression
Get
Return _LabelExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitOnErrorStatement(Me)
End Function
Public Function Update(onErrorKind As OnErrorStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression) As BoundOnErrorStatement
If onErrorKind <> Me.OnErrorKind OrElse labelOpt IsNot Me.LabelOpt OrElse labelExpressionOpt IsNot Me.LabelExpressionOpt Then
Dim result = New BoundOnErrorStatement(Me.Syntax, onErrorKind, labelOpt, labelExpressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionHandlingStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, containsOnError As Boolean, containsResume As Boolean, resumeWithoutLabelOpt As StatementSyntax, trackLineNumber As Boolean, body As BoundBlock, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionHandlingStatement, syntax, hasErrors OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ContainsOnError = containsOnError
Me._ContainsResume = containsResume
Me._ResumeWithoutLabelOpt = resumeWithoutLabelOpt
Me._TrackLineNumber = trackLineNumber
Me._Body = body
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ContainsOnError As Boolean
Public ReadOnly Property ContainsOnError As Boolean
Get
Return _ContainsOnError
End Get
End Property
Private ReadOnly _ContainsResume As Boolean
Public ReadOnly Property ContainsResume As Boolean
Get
Return _ContainsResume
End Get
End Property
Private ReadOnly _ResumeWithoutLabelOpt As StatementSyntax
Public ReadOnly Property ResumeWithoutLabelOpt As StatementSyntax
Get
Return _ResumeWithoutLabelOpt
End Get
End Property
Private ReadOnly _TrackLineNumber As Boolean
Public ReadOnly Property TrackLineNumber As Boolean
Get
Return _TrackLineNumber
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionHandlingStatement(Me)
End Function
Public Function Update(containsOnError As Boolean, containsResume As Boolean, resumeWithoutLabelOpt As StatementSyntax, trackLineNumber As Boolean, body As BoundBlock) As BoundUnstructuredExceptionHandlingStatement
If containsOnError <> Me.ContainsOnError OrElse containsResume <> Me.ContainsResume OrElse resumeWithoutLabelOpt IsNot Me.ResumeWithoutLabelOpt OrElse trackLineNumber <> Me.TrackLineNumber OrElse body IsNot Me.Body Then
Dim result = New BoundUnstructuredExceptionHandlingStatement(Me.Syntax, containsOnError, containsResume, resumeWithoutLabelOpt, trackLineNumber, body, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionHandlingCatchFilter
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, activeHandlerLocal As BoundLocal, resumeTargetLocal As BoundLocal, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionHandlingCatchFilter, syntax, type, hasErrors OrElse activeHandlerLocal.NonNullAndHasErrors() OrElse resumeTargetLocal.NonNullAndHasErrors())
Debug.Assert(activeHandlerLocal IsNot Nothing, "Field 'activeHandlerLocal' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(resumeTargetLocal IsNot Nothing, "Field 'resumeTargetLocal' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ActiveHandlerLocal = activeHandlerLocal
Me._ResumeTargetLocal = resumeTargetLocal
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ActiveHandlerLocal As BoundLocal
Public ReadOnly Property ActiveHandlerLocal As BoundLocal
Get
Return _ActiveHandlerLocal
End Get
End Property
Private ReadOnly _ResumeTargetLocal As BoundLocal
Public ReadOnly Property ResumeTargetLocal As BoundLocal
Get
Return _ResumeTargetLocal
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionHandlingCatchFilter(Me)
End Function
Public Function Update(activeHandlerLocal As BoundLocal, resumeTargetLocal As BoundLocal, type As TypeSymbol) As BoundUnstructuredExceptionHandlingCatchFilter
If activeHandlerLocal IsNot Me.ActiveHandlerLocal OrElse resumeTargetLocal IsNot Me.ResumeTargetLocal OrElse type IsNot Me.Type Then
Dim result = New BoundUnstructuredExceptionHandlingCatchFilter(Me.Syntax, activeHandlerLocal, resumeTargetLocal, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionOnErrorSwitch
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, value As BoundExpression, jumps As ImmutableArray(Of BoundGotoStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionOnErrorSwitch, syntax, hasErrors OrElse value.NonNullAndHasErrors() OrElse jumps.NonNullAndHasErrors())
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (jumps.IsDefault), "Field 'jumps' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Me._Jumps = jumps
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
Private ReadOnly _Jumps As ImmutableArray(Of BoundGotoStatement)
Public ReadOnly Property Jumps As ImmutableArray(Of BoundGotoStatement)
Get
Return _Jumps
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionOnErrorSwitch(Me)
End Function
Public Function Update(value As BoundExpression, jumps As ImmutableArray(Of BoundGotoStatement)) As BoundUnstructuredExceptionOnErrorSwitch
If value IsNot Me.Value OrElse jumps <> Me.Jumps Then
Dim result = New BoundUnstructuredExceptionOnErrorSwitch(Me.Syntax, value, jumps, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionResumeSwitch
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, resumeTargetTemporary As BoundLocal, resumeLabel As BoundLabelStatement, resumeNextLabel As BoundLabelStatement, jumps As ImmutableArray(Of BoundGotoStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionResumeSwitch, syntax, hasErrors OrElse resumeTargetTemporary.NonNullAndHasErrors() OrElse resumeLabel.NonNullAndHasErrors() OrElse resumeNextLabel.NonNullAndHasErrors() OrElse jumps.NonNullAndHasErrors())
Debug.Assert(resumeTargetTemporary IsNot Nothing, "Field 'resumeTargetTemporary' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(resumeLabel IsNot Nothing, "Field 'resumeLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(resumeNextLabel IsNot Nothing, "Field 'resumeNextLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (jumps.IsDefault), "Field 'jumps' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ResumeTargetTemporary = resumeTargetTemporary
Me._ResumeLabel = resumeLabel
Me._ResumeNextLabel = resumeNextLabel
Me._Jumps = jumps
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ResumeTargetTemporary As BoundLocal
Public ReadOnly Property ResumeTargetTemporary As BoundLocal
Get
Return _ResumeTargetTemporary
End Get
End Property
Private ReadOnly _ResumeLabel As BoundLabelStatement
Public ReadOnly Property ResumeLabel As BoundLabelStatement
Get
Return _ResumeLabel
End Get
End Property
Private ReadOnly _ResumeNextLabel As BoundLabelStatement
Public ReadOnly Property ResumeNextLabel As BoundLabelStatement
Get
Return _ResumeNextLabel
End Get
End Property
Private ReadOnly _Jumps As ImmutableArray(Of BoundGotoStatement)
Public ReadOnly Property Jumps As ImmutableArray(Of BoundGotoStatement)
Get
Return _Jumps
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionResumeSwitch(Me)
End Function
Public Function Update(resumeTargetTemporary As BoundLocal, resumeLabel As BoundLabelStatement, resumeNextLabel As BoundLabelStatement, jumps As ImmutableArray(Of BoundGotoStatement)) As BoundUnstructuredExceptionResumeSwitch
If resumeTargetTemporary IsNot Me.ResumeTargetTemporary OrElse resumeLabel IsNot Me.ResumeLabel OrElse resumeNextLabel IsNot Me.ResumeNextLabel OrElse jumps <> Me.Jumps Then
Dim result = New BoundUnstructuredExceptionResumeSwitch(Me.Syntax, resumeTargetTemporary, resumeLabel, resumeNextLabel, jumps, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAwaitOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, awaitableInstancePlaceholder As BoundRValuePlaceholder, getAwaiter As BoundExpression, awaiterInstancePlaceholder As BoundLValuePlaceholder, isCompleted As BoundExpression, getResult As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AwaitOperator, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse awaitableInstancePlaceholder.NonNullAndHasErrors() OrElse getAwaiter.NonNullAndHasErrors() OrElse awaiterInstancePlaceholder.NonNullAndHasErrors() OrElse isCompleted.NonNullAndHasErrors() OrElse getResult.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(awaitableInstancePlaceholder IsNot Nothing, "Field 'awaitableInstancePlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(getAwaiter IsNot Nothing, "Field 'getAwaiter' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(awaiterInstancePlaceholder IsNot Nothing, "Field 'awaiterInstancePlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(isCompleted IsNot Nothing, "Field 'isCompleted' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(getResult IsNot Nothing, "Field 'getResult' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._AwaitableInstancePlaceholder = awaitableInstancePlaceholder
Me._GetAwaiter = getAwaiter
Me._AwaiterInstancePlaceholder = awaiterInstancePlaceholder
Me._IsCompleted = isCompleted
Me._GetResult = getResult
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _AwaitableInstancePlaceholder As BoundRValuePlaceholder
Public ReadOnly Property AwaitableInstancePlaceholder As BoundRValuePlaceholder
Get
Return _AwaitableInstancePlaceholder
End Get
End Property
Private ReadOnly _GetAwaiter As BoundExpression
Public ReadOnly Property GetAwaiter As BoundExpression
Get
Return _GetAwaiter
End Get
End Property
Private ReadOnly _AwaiterInstancePlaceholder As BoundLValuePlaceholder
Public ReadOnly Property AwaiterInstancePlaceholder As BoundLValuePlaceholder
Get
Return _AwaiterInstancePlaceholder
End Get
End Property
Private ReadOnly _IsCompleted As BoundExpression
Public ReadOnly Property IsCompleted As BoundExpression
Get
Return _IsCompleted
End Get
End Property
Private ReadOnly _GetResult As BoundExpression
Public ReadOnly Property GetResult As BoundExpression
Get
Return _GetResult
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAwaitOperator(Me)
End Function
Public Function Update(operand As BoundExpression, awaitableInstancePlaceholder As BoundRValuePlaceholder, getAwaiter As BoundExpression, awaiterInstancePlaceholder As BoundLValuePlaceholder, isCompleted As BoundExpression, getResult As BoundExpression, type As TypeSymbol) As BoundAwaitOperator
If operand IsNot Me.Operand OrElse awaitableInstancePlaceholder IsNot Me.AwaitableInstancePlaceholder OrElse getAwaiter IsNot Me.GetAwaiter OrElse awaiterInstancePlaceholder IsNot Me.AwaiterInstancePlaceholder OrElse isCompleted IsNot Me.IsCompleted OrElse getResult IsNot Me.GetResult OrElse type IsNot Me.Type Then
Dim result = New BoundAwaitOperator(Me.Syntax, operand, awaitableInstancePlaceholder, getAwaiter, awaiterInstancePlaceholder, isCompleted, getResult, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSpillSequence
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, locals As ImmutableArray(Of LocalSymbol), spillFields As ImmutableArray(Of FieldSymbol), statements As ImmutableArray(Of BoundStatement), valueOpt As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SpillSequence, syntax, type, hasErrors OrElse statements.NonNullAndHasErrors() OrElse valueOpt.NonNullAndHasErrors())
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (spillFields.IsDefault), "Field 'spillFields' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (statements.IsDefault), "Field 'statements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Locals = locals
Me._SpillFields = spillFields
Me._Statements = statements
Me._ValueOpt = valueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
Private ReadOnly _SpillFields As ImmutableArray(Of FieldSymbol)
Public ReadOnly Property SpillFields As ImmutableArray(Of FieldSymbol)
Get
Return _SpillFields
End Get
End Property
Private ReadOnly _Statements As ImmutableArray(Of BoundStatement)
Public ReadOnly Property Statements As ImmutableArray(Of BoundStatement)
Get
Return _Statements
End Get
End Property
Private ReadOnly _ValueOpt As BoundExpression
Public ReadOnly Property ValueOpt As BoundExpression
Get
Return _ValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSpillSequence(Me)
End Function
Public Function Update(locals As ImmutableArray(Of LocalSymbol), spillFields As ImmutableArray(Of FieldSymbol), statements As ImmutableArray(Of BoundStatement), valueOpt As BoundExpression, type As TypeSymbol) As BoundSpillSequence
If locals <> Me.Locals OrElse spillFields <> Me.SpillFields OrElse statements <> Me.Statements OrElse valueOpt IsNot Me.ValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundSpillSequence(Me.Syntax, locals, spillFields, statements, valueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundStopStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyBase.New(BoundKind.StopStatement, syntax, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode)
MyBase.New(BoundKind.StopStatement, syntax)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitStopStatement(Me)
End Function
End Class
Partial Friend NotInheritable Class BoundEndStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyBase.New(BoundKind.EndStatement, syntax, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode)
MyBase.New(BoundKind.EndStatement, syntax)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitEndStatement(Me)
End Function
End Class
Partial Friend NotInheritable Class BoundMidResult
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, original As BoundExpression, start As BoundExpression, lengthOpt As BoundExpression, source As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.MidResult, syntax, type, hasErrors OrElse original.NonNullAndHasErrors() OrElse start.NonNullAndHasErrors() OrElse lengthOpt.NonNullAndHasErrors() OrElse source.NonNullAndHasErrors())
Debug.Assert(original IsNot Nothing, "Field 'original' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(start IsNot Nothing, "Field 'start' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(source IsNot Nothing, "Field 'source' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Original = original
Me._Start = start
Me._LengthOpt = lengthOpt
Me._Source = source
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Original As BoundExpression
Public ReadOnly Property Original As BoundExpression
Get
Return _Original
End Get
End Property
Private ReadOnly _Start As BoundExpression
Public ReadOnly Property Start As BoundExpression
Get
Return _Start
End Get
End Property
Private ReadOnly _LengthOpt As BoundExpression
Public ReadOnly Property LengthOpt As BoundExpression
Get
Return _LengthOpt
End Get
End Property
Private ReadOnly _Source As BoundExpression
Public ReadOnly Property Source As BoundExpression
Get
Return _Source
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMidResult(Me)
End Function
Public Function Update(original As BoundExpression, start As BoundExpression, lengthOpt As BoundExpression, source As BoundExpression, type As TypeSymbol) As BoundMidResult
If original IsNot Me.Original OrElse start IsNot Me.Start OrElse lengthOpt IsNot Me.LengthOpt OrElse source IsNot Me.Source OrElse type IsNot Me.Type Then
Dim result = New BoundMidResult(Me.Syntax, original, start, lengthOpt, source, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConditionalAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiver As BoundExpression, placeholder As BoundRValuePlaceholder, accessExpression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConditionalAccess, syntax, type, hasErrors OrElse receiver.NonNullAndHasErrors() OrElse placeholder.NonNullAndHasErrors() OrElse accessExpression.NonNullAndHasErrors())
Debug.Assert(receiver IsNot Nothing, "Field 'receiver' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(placeholder IsNot Nothing, "Field 'placeholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(accessExpression IsNot Nothing, "Field 'accessExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Receiver = receiver
Me._Placeholder = placeholder
Me._AccessExpression = accessExpression
End Sub
Private ReadOnly _Receiver As BoundExpression
Public ReadOnly Property Receiver As BoundExpression
Get
Return _Receiver
End Get
End Property
Private ReadOnly _Placeholder As BoundRValuePlaceholder
Public ReadOnly Property Placeholder As BoundRValuePlaceholder
Get
Return _Placeholder
End Get
End Property
Private ReadOnly _AccessExpression As BoundExpression
Public ReadOnly Property AccessExpression As BoundExpression
Get
Return _AccessExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConditionalAccess(Me)
End Function
Public Function Update(receiver As BoundExpression, placeholder As BoundRValuePlaceholder, accessExpression As BoundExpression, type As TypeSymbol) As BoundConditionalAccess
If receiver IsNot Me.Receiver OrElse placeholder IsNot Me.Placeholder OrElse accessExpression IsNot Me.AccessExpression OrElse type IsNot Me.Type Then
Dim result = New BoundConditionalAccess(Me.Syntax, receiver, placeholder, accessExpression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConditionalAccessReceiverPlaceholder
Inherits BoundRValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, placeholderId As Integer, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ConditionalAccessReceiverPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PlaceholderId = placeholderId
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, placeholderId As Integer, type As TypeSymbol)
MyBase.New(BoundKind.ConditionalAccessReceiverPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PlaceholderId = placeholderId
Validate()
End Sub
Private ReadOnly _PlaceholderId As Integer
Public ReadOnly Property PlaceholderId As Integer
Get
Return _PlaceholderId
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConditionalAccessReceiverPlaceholder(Me)
End Function
Public Function Update(placeholderId As Integer, type As TypeSymbol) As BoundConditionalAccessReceiverPlaceholder
If placeholderId <> Me.PlaceholderId OrElse type IsNot Me.Type Then
Dim result = New BoundConditionalAccessReceiverPlaceholder(Me.Syntax, placeholderId, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLoweredConditionalAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOrCondition As BoundExpression, captureReceiver As Boolean, placeholderId As Integer, whenNotNull As BoundExpression, whenNullOpt As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LoweredConditionalAccess, syntax, type, hasErrors OrElse receiverOrCondition.NonNullAndHasErrors() OrElse whenNotNull.NonNullAndHasErrors() OrElse whenNullOpt.NonNullAndHasErrors())
Debug.Assert(receiverOrCondition IsNot Nothing, "Field 'receiverOrCondition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(whenNotNull IsNot Nothing, "Field 'whenNotNull' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOrCondition = receiverOrCondition
Me._CaptureReceiver = captureReceiver
Me._PlaceholderId = placeholderId
Me._WhenNotNull = whenNotNull
Me._WhenNullOpt = whenNullOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ReceiverOrCondition As BoundExpression
Public ReadOnly Property ReceiverOrCondition As BoundExpression
Get
Return _ReceiverOrCondition
End Get
End Property
Private ReadOnly _CaptureReceiver As Boolean
Public ReadOnly Property CaptureReceiver As Boolean
Get
Return _CaptureReceiver
End Get
End Property
Private ReadOnly _PlaceholderId As Integer
Public ReadOnly Property PlaceholderId As Integer
Get
Return _PlaceholderId
End Get
End Property
Private ReadOnly _WhenNotNull As BoundExpression
Public ReadOnly Property WhenNotNull As BoundExpression
Get
Return _WhenNotNull
End Get
End Property
Private ReadOnly _WhenNullOpt As BoundExpression
Public ReadOnly Property WhenNullOpt As BoundExpression
Get
Return _WhenNullOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLoweredConditionalAccess(Me)
End Function
Public Function Update(receiverOrCondition As BoundExpression, captureReceiver As Boolean, placeholderId As Integer, whenNotNull As BoundExpression, whenNullOpt As BoundExpression, type As TypeSymbol) As BoundLoweredConditionalAccess
If receiverOrCondition IsNot Me.ReceiverOrCondition OrElse captureReceiver <> Me.CaptureReceiver OrElse placeholderId <> Me.PlaceholderId OrElse whenNotNull IsNot Me.WhenNotNull OrElse whenNullOpt IsNot Me.WhenNullOpt OrElse type IsNot Me.Type Then
Dim result = New BoundLoweredConditionalAccess(Me.Syntax, receiverOrCondition, captureReceiver, placeholderId, whenNotNull, whenNullOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundComplexConditionalAccessReceiver
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, valueTypeReceiver As BoundExpression, referenceTypeReceiver As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ComplexConditionalAccessReceiver, syntax, type, hasErrors OrElse valueTypeReceiver.NonNullAndHasErrors() OrElse referenceTypeReceiver.NonNullAndHasErrors())
Debug.Assert(valueTypeReceiver IsNot Nothing, "Field 'valueTypeReceiver' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(referenceTypeReceiver IsNot Nothing, "Field 'referenceTypeReceiver' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ValueTypeReceiver = valueTypeReceiver
Me._ReferenceTypeReceiver = referenceTypeReceiver
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ValueTypeReceiver As BoundExpression
Public ReadOnly Property ValueTypeReceiver As BoundExpression
Get
Return _ValueTypeReceiver
End Get
End Property
Private ReadOnly _ReferenceTypeReceiver As BoundExpression
Public ReadOnly Property ReferenceTypeReceiver As BoundExpression
Get
Return _ReferenceTypeReceiver
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitComplexConditionalAccessReceiver(Me)
End Function
Public Function Update(valueTypeReceiver As BoundExpression, referenceTypeReceiver As BoundExpression, type As TypeSymbol) As BoundComplexConditionalAccessReceiver
If valueTypeReceiver IsNot Me.ValueTypeReceiver OrElse referenceTypeReceiver IsNot Me.ReferenceTypeReceiver OrElse type IsNot Me.Type Then
Dim result = New BoundComplexConditionalAccessReceiver(Me.Syntax, valueTypeReceiver, referenceTypeReceiver, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNameOfOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, argument As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NameOfOperator, syntax, type, hasErrors OrElse argument.NonNullAndHasErrors())
Debug.Assert(argument IsNot Nothing, "Field 'argument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Argument = argument
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Argument As BoundExpression
Public ReadOnly Property Argument As BoundExpression
Get
Return _Argument
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNameOfOperator(Me)
End Function
Public Function Update(argument As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundNameOfOperator
If argument IsNot Me.Argument OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundNameOfOperator(Me.Syntax, argument, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeAsValueExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundTypeExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TypeAsValueExpression, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundTypeExpression
Public ReadOnly Property Expression As BoundTypeExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeAsValueExpression(Me)
End Function
Public Function Update(expression As BoundTypeExpression, type As TypeSymbol) As BoundTypeAsValueExpression
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundTypeAsValueExpression(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundInterpolatedStringExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, contents As ImmutableArray(Of BoundNode), binder As Binder, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.InterpolatedStringExpression, syntax, type, hasErrors OrElse contents.NonNullAndHasErrors())
Debug.Assert(Not (contents.IsDefault), "Field 'contents' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Contents = contents
Me._Binder = binder
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Contents As ImmutableArray(Of BoundNode)
Public ReadOnly Property Contents As ImmutableArray(Of BoundNode)
Get
Return _Contents
End Get
End Property
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInterpolatedStringExpression(Me)
End Function
Public Function Update(contents As ImmutableArray(Of BoundNode), binder As Binder, type As TypeSymbol) As BoundInterpolatedStringExpression
If contents <> Me.Contents OrElse binder IsNot Me.Binder OrElse type IsNot Me.Type Then
Dim result = New BoundInterpolatedStringExpression(Me.Syntax, contents, binder, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundInterpolation
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, alignmentOpt As BoundExpression, formatStringOpt As BoundLiteral, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Interpolation, syntax, hasErrors OrElse expression.NonNullAndHasErrors() OrElse alignmentOpt.NonNullAndHasErrors() OrElse formatStringOpt.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Me._AlignmentOpt = alignmentOpt
Me._FormatStringOpt = formatStringOpt
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _AlignmentOpt As BoundExpression
Public ReadOnly Property AlignmentOpt As BoundExpression
Get
Return _AlignmentOpt
End Get
End Property
Private ReadOnly _FormatStringOpt As BoundLiteral
Public ReadOnly Property FormatStringOpt As BoundLiteral
Get
Return _FormatStringOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInterpolation(Me)
End Function
Public Function Update(expression As BoundExpression, alignmentOpt As BoundExpression, formatStringOpt As BoundLiteral) As BoundInterpolation
If expression IsNot Me.Expression OrElse alignmentOpt IsNot Me.AlignmentOpt OrElse formatStringOpt IsNot Me.FormatStringOpt Then
Dim result = New BoundInterpolation(Me.Syntax, expression, alignmentOpt, formatStringOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Friend MustInherit Partial Class BoundTreeVisitor(Of A, R)
<MethodImpl(MethodImplOptions.NoInlining), DebuggerStepThrough>
Friend Function VisitInternal(node As BoundNode, arg As A) As R
Select Case node.Kind
Case BoundKind.TypeArguments
Return VisitTypeArguments(CType(node, BoundTypeArguments), arg)
Case BoundKind.OmittedArgument
Return VisitOmittedArgument(CType(node, BoundOmittedArgument), arg)
Case BoundKind.LValueToRValueWrapper
Return VisitLValueToRValueWrapper(CType(node, BoundLValueToRValueWrapper), arg)
Case BoundKind.WithLValueExpressionPlaceholder
Return VisitWithLValueExpressionPlaceholder(CType(node, BoundWithLValueExpressionPlaceholder), arg)
Case BoundKind.WithRValueExpressionPlaceholder
Return VisitWithRValueExpressionPlaceholder(CType(node, BoundWithRValueExpressionPlaceholder), arg)
Case BoundKind.RValuePlaceholder
Return VisitRValuePlaceholder(CType(node, BoundRValuePlaceholder), arg)
Case BoundKind.LValuePlaceholder
Return VisitLValuePlaceholder(CType(node, BoundLValuePlaceholder), arg)
Case BoundKind.Dup
Return VisitDup(CType(node, BoundDup), arg)
Case BoundKind.BadExpression
Return VisitBadExpression(CType(node, BoundBadExpression), arg)
Case BoundKind.BadStatement
Return VisitBadStatement(CType(node, BoundBadStatement), arg)
Case BoundKind.Parenthesized
Return VisitParenthesized(CType(node, BoundParenthesized), arg)
Case BoundKind.BadVariable
Return VisitBadVariable(CType(node, BoundBadVariable), arg)
Case BoundKind.ArrayAccess
Return VisitArrayAccess(CType(node, BoundArrayAccess), arg)
Case BoundKind.ArrayLength
Return VisitArrayLength(CType(node, BoundArrayLength), arg)
Case BoundKind.[GetType]
Return VisitGetType(CType(node, BoundGetType), arg)
Case BoundKind.FieldInfo
Return VisitFieldInfo(CType(node, BoundFieldInfo), arg)
Case BoundKind.MethodInfo
Return VisitMethodInfo(CType(node, BoundMethodInfo), arg)
Case BoundKind.TypeExpression
Return VisitTypeExpression(CType(node, BoundTypeExpression), arg)
Case BoundKind.TypeOrValueExpression
Return VisitTypeOrValueExpression(CType(node, BoundTypeOrValueExpression), arg)
Case BoundKind.NamespaceExpression
Return VisitNamespaceExpression(CType(node, BoundNamespaceExpression), arg)
Case BoundKind.MethodDefIndex
Return VisitMethodDefIndex(CType(node, BoundMethodDefIndex), arg)
Case BoundKind.MaximumMethodDefIndex
Return VisitMaximumMethodDefIndex(CType(node, BoundMaximumMethodDefIndex), arg)
Case BoundKind.InstrumentationPayloadRoot
Return VisitInstrumentationPayloadRoot(CType(node, BoundInstrumentationPayloadRoot), arg)
Case BoundKind.ModuleVersionId
Return VisitModuleVersionId(CType(node, BoundModuleVersionId), arg)
Case BoundKind.ModuleVersionIdString
Return VisitModuleVersionIdString(CType(node, BoundModuleVersionIdString), arg)
Case BoundKind.SourceDocumentIndex
Return VisitSourceDocumentIndex(CType(node, BoundSourceDocumentIndex), arg)
Case BoundKind.UnaryOperator
Return VisitUnaryOperator(CType(node, BoundUnaryOperator), arg)
Case BoundKind.UserDefinedUnaryOperator
Return VisitUserDefinedUnaryOperator(CType(node, BoundUserDefinedUnaryOperator), arg)
Case BoundKind.NullableIsTrueOperator
Return VisitNullableIsTrueOperator(CType(node, BoundNullableIsTrueOperator), arg)
Case BoundKind.BinaryOperator
Return VisitBinaryOperator(CType(node, BoundBinaryOperator), arg)
Case BoundKind.UserDefinedBinaryOperator
Return VisitUserDefinedBinaryOperator(CType(node, BoundUserDefinedBinaryOperator), arg)
Case BoundKind.UserDefinedShortCircuitingOperator
Return VisitUserDefinedShortCircuitingOperator(CType(node, BoundUserDefinedShortCircuitingOperator), arg)
Case BoundKind.CompoundAssignmentTargetPlaceholder
Return VisitCompoundAssignmentTargetPlaceholder(CType(node, BoundCompoundAssignmentTargetPlaceholder), arg)
Case BoundKind.AssignmentOperator
Return VisitAssignmentOperator(CType(node, BoundAssignmentOperator), arg)
Case BoundKind.ReferenceAssignment
Return VisitReferenceAssignment(CType(node, BoundReferenceAssignment), arg)
Case BoundKind.AddressOfOperator
Return VisitAddressOfOperator(CType(node, BoundAddressOfOperator), arg)
Case BoundKind.TernaryConditionalExpression
Return VisitTernaryConditionalExpression(CType(node, BoundTernaryConditionalExpression), arg)
Case BoundKind.BinaryConditionalExpression
Return VisitBinaryConditionalExpression(CType(node, BoundBinaryConditionalExpression), arg)
Case BoundKind.Conversion
Return VisitConversion(CType(node, BoundConversion), arg)
Case BoundKind.RelaxationLambda
Return VisitRelaxationLambda(CType(node, BoundRelaxationLambda), arg)
Case BoundKind.ConvertedTupleElements
Return VisitConvertedTupleElements(CType(node, BoundConvertedTupleElements), arg)
Case BoundKind.UserDefinedConversion
Return VisitUserDefinedConversion(CType(node, BoundUserDefinedConversion), arg)
Case BoundKind.[DirectCast]
Return VisitDirectCast(CType(node, BoundDirectCast), arg)
Case BoundKind.[TryCast]
Return VisitTryCast(CType(node, BoundTryCast), arg)
Case BoundKind.[TypeOf]
Return VisitTypeOf(CType(node, BoundTypeOf), arg)
Case BoundKind.SequencePoint
Return VisitSequencePoint(CType(node, BoundSequencePoint), arg)
Case BoundKind.SequencePointExpression
Return VisitSequencePointExpression(CType(node, BoundSequencePointExpression), arg)
Case BoundKind.SequencePointWithSpan
Return VisitSequencePointWithSpan(CType(node, BoundSequencePointWithSpan), arg)
Case BoundKind.NoOpStatement
Return VisitNoOpStatement(CType(node, BoundNoOpStatement), arg)
Case BoundKind.MethodGroup
Return VisitMethodGroup(CType(node, BoundMethodGroup), arg)
Case BoundKind.PropertyGroup
Return VisitPropertyGroup(CType(node, BoundPropertyGroup), arg)
Case BoundKind.ReturnStatement
Return VisitReturnStatement(CType(node, BoundReturnStatement), arg)
Case BoundKind.YieldStatement
Return VisitYieldStatement(CType(node, BoundYieldStatement), arg)
Case BoundKind.ThrowStatement
Return VisitThrowStatement(CType(node, BoundThrowStatement), arg)
Case BoundKind.RedimStatement
Return VisitRedimStatement(CType(node, BoundRedimStatement), arg)
Case BoundKind.RedimClause
Return VisitRedimClause(CType(node, BoundRedimClause), arg)
Case BoundKind.EraseStatement
Return VisitEraseStatement(CType(node, BoundEraseStatement), arg)
Case BoundKind.[Call]
Return VisitCall(CType(node, BoundCall), arg)
Case BoundKind.Attribute
Return VisitAttribute(CType(node, BoundAttribute), arg)
Case BoundKind.LateMemberAccess
Return VisitLateMemberAccess(CType(node, BoundLateMemberAccess), arg)
Case BoundKind.LateInvocation
Return VisitLateInvocation(CType(node, BoundLateInvocation), arg)
Case BoundKind.LateAddressOfOperator
Return VisitLateAddressOfOperator(CType(node, BoundLateAddressOfOperator), arg)
Case BoundKind.TupleLiteral
Return VisitTupleLiteral(CType(node, BoundTupleLiteral), arg)
Case BoundKind.ConvertedTupleLiteral
Return VisitConvertedTupleLiteral(CType(node, BoundConvertedTupleLiteral), arg)
Case BoundKind.ObjectCreationExpression
Return VisitObjectCreationExpression(CType(node, BoundObjectCreationExpression), arg)
Case BoundKind.NoPiaObjectCreationExpression
Return VisitNoPiaObjectCreationExpression(CType(node, BoundNoPiaObjectCreationExpression), arg)
Case BoundKind.AnonymousTypeCreationExpression
Return VisitAnonymousTypeCreationExpression(CType(node, BoundAnonymousTypeCreationExpression), arg)
Case BoundKind.AnonymousTypePropertyAccess
Return VisitAnonymousTypePropertyAccess(CType(node, BoundAnonymousTypePropertyAccess), arg)
Case BoundKind.AnonymousTypeFieldInitializer
Return VisitAnonymousTypeFieldInitializer(CType(node, BoundAnonymousTypeFieldInitializer), arg)
Case BoundKind.ObjectInitializerExpression
Return VisitObjectInitializerExpression(CType(node, BoundObjectInitializerExpression), arg)
Case BoundKind.CollectionInitializerExpression
Return VisitCollectionInitializerExpression(CType(node, BoundCollectionInitializerExpression), arg)
Case BoundKind.NewT
Return VisitNewT(CType(node, BoundNewT), arg)
Case BoundKind.DelegateCreationExpression
Return VisitDelegateCreationExpression(CType(node, BoundDelegateCreationExpression), arg)
Case BoundKind.ArrayCreation
Return VisitArrayCreation(CType(node, BoundArrayCreation), arg)
Case BoundKind.ArrayLiteral
Return VisitArrayLiteral(CType(node, BoundArrayLiteral), arg)
Case BoundKind.ArrayInitialization
Return VisitArrayInitialization(CType(node, BoundArrayInitialization), arg)
Case BoundKind.FieldAccess
Return VisitFieldAccess(CType(node, BoundFieldAccess), arg)
Case BoundKind.PropertyAccess
Return VisitPropertyAccess(CType(node, BoundPropertyAccess), arg)
Case BoundKind.EventAccess
Return VisitEventAccess(CType(node, BoundEventAccess), arg)
Case BoundKind.Block
Return VisitBlock(CType(node, BoundBlock), arg)
Case BoundKind.StateMachineScope
Return VisitStateMachineScope(CType(node, BoundStateMachineScope), arg)
Case BoundKind.LocalDeclaration
Return VisitLocalDeclaration(CType(node, BoundLocalDeclaration), arg)
Case BoundKind.AsNewLocalDeclarations
Return VisitAsNewLocalDeclarations(CType(node, BoundAsNewLocalDeclarations), arg)
Case BoundKind.DimStatement
Return VisitDimStatement(CType(node, BoundDimStatement), arg)
Case BoundKind.Initializer
Return VisitInitializer(CType(node, BoundInitializer), arg)
Case BoundKind.FieldInitializer
Return VisitFieldInitializer(CType(node, BoundFieldInitializer), arg)
Case BoundKind.PropertyInitializer
Return VisitPropertyInitializer(CType(node, BoundPropertyInitializer), arg)
Case BoundKind.ParameterEqualsValue
Return VisitParameterEqualsValue(CType(node, BoundParameterEqualsValue), arg)
Case BoundKind.GlobalStatementInitializer
Return VisitGlobalStatementInitializer(CType(node, BoundGlobalStatementInitializer), arg)
Case BoundKind.Sequence
Return VisitSequence(CType(node, BoundSequence), arg)
Case BoundKind.ExpressionStatement
Return VisitExpressionStatement(CType(node, BoundExpressionStatement), arg)
Case BoundKind.IfStatement
Return VisitIfStatement(CType(node, BoundIfStatement), arg)
Case BoundKind.SelectStatement
Return VisitSelectStatement(CType(node, BoundSelectStatement), arg)
Case BoundKind.CaseBlock
Return VisitCaseBlock(CType(node, BoundCaseBlock), arg)
Case BoundKind.CaseStatement
Return VisitCaseStatement(CType(node, BoundCaseStatement), arg)
Case BoundKind.SimpleCaseClause
Return VisitSimpleCaseClause(CType(node, BoundSimpleCaseClause), arg)
Case BoundKind.RangeCaseClause
Return VisitRangeCaseClause(CType(node, BoundRangeCaseClause), arg)
Case BoundKind.RelationalCaseClause
Return VisitRelationalCaseClause(CType(node, BoundRelationalCaseClause), arg)
Case BoundKind.DoLoopStatement
Return VisitDoLoopStatement(CType(node, BoundDoLoopStatement), arg)
Case BoundKind.WhileStatement
Return VisitWhileStatement(CType(node, BoundWhileStatement), arg)
Case BoundKind.ForToUserDefinedOperators
Return VisitForToUserDefinedOperators(CType(node, BoundForToUserDefinedOperators), arg)
Case BoundKind.ForToStatement
Return VisitForToStatement(CType(node, BoundForToStatement), arg)
Case BoundKind.ForEachStatement
Return VisitForEachStatement(CType(node, BoundForEachStatement), arg)
Case BoundKind.ExitStatement
Return VisitExitStatement(CType(node, BoundExitStatement), arg)
Case BoundKind.ContinueStatement
Return VisitContinueStatement(CType(node, BoundContinueStatement), arg)
Case BoundKind.TryStatement
Return VisitTryStatement(CType(node, BoundTryStatement), arg)
Case BoundKind.CatchBlock
Return VisitCatchBlock(CType(node, BoundCatchBlock), arg)
Case BoundKind.Literal
Return VisitLiteral(CType(node, BoundLiteral), arg)
Case BoundKind.MeReference
Return VisitMeReference(CType(node, BoundMeReference), arg)
Case BoundKind.ValueTypeMeReference
Return VisitValueTypeMeReference(CType(node, BoundValueTypeMeReference), arg)
Case BoundKind.MyBaseReference
Return VisitMyBaseReference(CType(node, BoundMyBaseReference), arg)
Case BoundKind.MyClassReference
Return VisitMyClassReference(CType(node, BoundMyClassReference), arg)
Case BoundKind.PreviousSubmissionReference
Return VisitPreviousSubmissionReference(CType(node, BoundPreviousSubmissionReference), arg)
Case BoundKind.HostObjectMemberReference
Return VisitHostObjectMemberReference(CType(node, BoundHostObjectMemberReference), arg)
Case BoundKind.Local
Return VisitLocal(CType(node, BoundLocal), arg)
Case BoundKind.PseudoVariable
Return VisitPseudoVariable(CType(node, BoundPseudoVariable), arg)
Case BoundKind.Parameter
Return VisitParameter(CType(node, BoundParameter), arg)
Case BoundKind.ByRefArgumentPlaceholder
Return VisitByRefArgumentPlaceholder(CType(node, BoundByRefArgumentPlaceholder), arg)
Case BoundKind.ByRefArgumentWithCopyBack
Return VisitByRefArgumentWithCopyBack(CType(node, BoundByRefArgumentWithCopyBack), arg)
Case BoundKind.LateBoundArgumentSupportingAssignmentWithCapture
Return VisitLateBoundArgumentSupportingAssignmentWithCapture(CType(node, BoundLateBoundArgumentSupportingAssignmentWithCapture), arg)
Case BoundKind.LabelStatement
Return VisitLabelStatement(CType(node, BoundLabelStatement), arg)
Case BoundKind.Label
Return VisitLabel(CType(node, BoundLabel), arg)
Case BoundKind.GotoStatement
Return VisitGotoStatement(CType(node, BoundGotoStatement), arg)
Case BoundKind.StatementList
Return VisitStatementList(CType(node, BoundStatementList), arg)
Case BoundKind.ConditionalGoto
Return VisitConditionalGoto(CType(node, BoundConditionalGoto), arg)
Case BoundKind.WithStatement
Return VisitWithStatement(CType(node, BoundWithStatement), arg)
Case BoundKind.UnboundLambda
Return VisitUnboundLambda(CType(node, UnboundLambda), arg)
Case BoundKind.Lambda
Return VisitLambda(CType(node, BoundLambda), arg)
Case BoundKind.QueryExpression
Return VisitQueryExpression(CType(node, BoundQueryExpression), arg)
Case BoundKind.QuerySource
Return VisitQuerySource(CType(node, BoundQuerySource), arg)
Case BoundKind.ToQueryableCollectionConversion
Return VisitToQueryableCollectionConversion(CType(node, BoundToQueryableCollectionConversion), arg)
Case BoundKind.QueryableSource
Return VisitQueryableSource(CType(node, BoundQueryableSource), arg)
Case BoundKind.QueryClause
Return VisitQueryClause(CType(node, BoundQueryClause), arg)
Case BoundKind.Ordering
Return VisitOrdering(CType(node, BoundOrdering), arg)
Case BoundKind.QueryLambda
Return VisitQueryLambda(CType(node, BoundQueryLambda), arg)
Case BoundKind.RangeVariableAssignment
Return VisitRangeVariableAssignment(CType(node, BoundRangeVariableAssignment), arg)
Case BoundKind.GroupTypeInferenceLambda
Return VisitGroupTypeInferenceLambda(CType(node, GroupTypeInferenceLambda), arg)
Case BoundKind.AggregateClause
Return VisitAggregateClause(CType(node, BoundAggregateClause), arg)
Case BoundKind.GroupAggregation
Return VisitGroupAggregation(CType(node, BoundGroupAggregation), arg)
Case BoundKind.RangeVariable
Return VisitRangeVariable(CType(node, BoundRangeVariable), arg)
Case BoundKind.AddHandlerStatement
Return VisitAddHandlerStatement(CType(node, BoundAddHandlerStatement), arg)
Case BoundKind.RemoveHandlerStatement
Return VisitRemoveHandlerStatement(CType(node, BoundRemoveHandlerStatement), arg)
Case BoundKind.RaiseEventStatement
Return VisitRaiseEventStatement(CType(node, BoundRaiseEventStatement), arg)
Case BoundKind.UsingStatement
Return VisitUsingStatement(CType(node, BoundUsingStatement), arg)
Case BoundKind.SyncLockStatement
Return VisitSyncLockStatement(CType(node, BoundSyncLockStatement), arg)
Case BoundKind.XmlName
Return VisitXmlName(CType(node, BoundXmlName), arg)
Case BoundKind.XmlNamespace
Return VisitXmlNamespace(CType(node, BoundXmlNamespace), arg)
Case BoundKind.XmlDocument
Return VisitXmlDocument(CType(node, BoundXmlDocument), arg)
Case BoundKind.XmlDeclaration
Return VisitXmlDeclaration(CType(node, BoundXmlDeclaration), arg)
Case BoundKind.XmlProcessingInstruction
Return VisitXmlProcessingInstruction(CType(node, BoundXmlProcessingInstruction), arg)
Case BoundKind.XmlComment
Return VisitXmlComment(CType(node, BoundXmlComment), arg)
Case BoundKind.XmlAttribute
Return VisitXmlAttribute(CType(node, BoundXmlAttribute), arg)
Case BoundKind.XmlElement
Return VisitXmlElement(CType(node, BoundXmlElement), arg)
Case BoundKind.XmlMemberAccess
Return VisitXmlMemberAccess(CType(node, BoundXmlMemberAccess), arg)
Case BoundKind.XmlEmbeddedExpression
Return VisitXmlEmbeddedExpression(CType(node, BoundXmlEmbeddedExpression), arg)
Case BoundKind.XmlCData
Return VisitXmlCData(CType(node, BoundXmlCData), arg)
Case BoundKind.ResumeStatement
Return VisitResumeStatement(CType(node, BoundResumeStatement), arg)
Case BoundKind.OnErrorStatement
Return VisitOnErrorStatement(CType(node, BoundOnErrorStatement), arg)
Case BoundKind.UnstructuredExceptionHandlingStatement
Return VisitUnstructuredExceptionHandlingStatement(CType(node, BoundUnstructuredExceptionHandlingStatement), arg)
Case BoundKind.UnstructuredExceptionHandlingCatchFilter
Return VisitUnstructuredExceptionHandlingCatchFilter(CType(node, BoundUnstructuredExceptionHandlingCatchFilter), arg)
Case BoundKind.UnstructuredExceptionOnErrorSwitch
Return VisitUnstructuredExceptionOnErrorSwitch(CType(node, BoundUnstructuredExceptionOnErrorSwitch), arg)
Case BoundKind.UnstructuredExceptionResumeSwitch
Return VisitUnstructuredExceptionResumeSwitch(CType(node, BoundUnstructuredExceptionResumeSwitch), arg)
Case BoundKind.AwaitOperator
Return VisitAwaitOperator(CType(node, BoundAwaitOperator), arg)
Case BoundKind.SpillSequence
Return VisitSpillSequence(CType(node, BoundSpillSequence), arg)
Case BoundKind.StopStatement
Return VisitStopStatement(CType(node, BoundStopStatement), arg)
Case BoundKind.EndStatement
Return VisitEndStatement(CType(node, BoundEndStatement), arg)
Case BoundKind.MidResult
Return VisitMidResult(CType(node, BoundMidResult), arg)
Case BoundKind.ConditionalAccess
Return VisitConditionalAccess(CType(node, BoundConditionalAccess), arg)
Case BoundKind.ConditionalAccessReceiverPlaceholder
Return VisitConditionalAccessReceiverPlaceholder(CType(node, BoundConditionalAccessReceiverPlaceholder), arg)
Case BoundKind.LoweredConditionalAccess
Return VisitLoweredConditionalAccess(CType(node, BoundLoweredConditionalAccess), arg)
Case BoundKind.ComplexConditionalAccessReceiver
Return VisitComplexConditionalAccessReceiver(CType(node, BoundComplexConditionalAccessReceiver), arg)
Case BoundKind.NameOfOperator
Return VisitNameOfOperator(CType(node, BoundNameOfOperator), arg)
Case BoundKind.TypeAsValueExpression
Return VisitTypeAsValueExpression(CType(node, BoundTypeAsValueExpression), arg)
Case BoundKind.InterpolatedStringExpression
Return VisitInterpolatedStringExpression(CType(node, BoundInterpolatedStringExpression), arg)
Case BoundKind.Interpolation
Return VisitInterpolation(CType(node, BoundInterpolation), arg)
End Select
Return DefaultVisit(node, arg)
End Function
End Class
Friend MustInherit Partial Class BoundTreeVisitor(Of A, R)
Public Overridable Function VisitTypeArguments(node As BoundTypeArguments, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitOmittedArgument(node As BoundOmittedArgument, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRValuePlaceholder(node As BoundRValuePlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLValuePlaceholder(node As BoundLValuePlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDup(node As BoundDup, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBadExpression(node As BoundBadExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBadStatement(node As BoundBadStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitParenthesized(node As BoundParenthesized, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBadVariable(node As BoundBadVariable, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayAccess(node As BoundArrayAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayLength(node As BoundArrayLength, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGetType(node As BoundGetType, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitFieldInfo(node As BoundFieldInfo, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMethodInfo(node As BoundMethodInfo, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeExpression(node As BoundTypeExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNamespaceExpression(node As BoundNamespaceExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMethodDefIndex(node As BoundMethodDefIndex, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitModuleVersionId(node As BoundModuleVersionId, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitModuleVersionIdString(node As BoundModuleVersionIdString, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnaryOperator(node As BoundUnaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBinaryOperator(node As BoundBinaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAssignmentOperator(node As BoundAssignmentOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitReferenceAssignment(node As BoundReferenceAssignment, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAddressOfOperator(node As BoundAddressOfOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConversion(node As BoundConversion, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRelaxationLambda(node As BoundRelaxationLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConvertedTupleElements(node As BoundConvertedTupleElements, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedConversion(node As BoundUserDefinedConversion, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDirectCast(node As BoundDirectCast, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTryCast(node As BoundTryCast, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeOf(node As BoundTypeOf, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequencePoint(node As BoundSequencePoint, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequencePointExpression(node As BoundSequencePointExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNoOpStatement(node As BoundNoOpStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMethodGroup(node As BoundMethodGroup, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPropertyGroup(node As BoundPropertyGroup, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitReturnStatement(node As BoundReturnStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitYieldStatement(node As BoundYieldStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitThrowStatement(node As BoundThrowStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRedimStatement(node As BoundRedimStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRedimClause(node As BoundRedimClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitEraseStatement(node As BoundEraseStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCall(node As BoundCall, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAttribute(node As BoundAttribute, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateMemberAccess(node As BoundLateMemberAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateInvocation(node As BoundLateInvocation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTupleLiteral(node As BoundTupleLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitObjectCreationExpression(node As BoundObjectCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNewT(node As BoundNewT, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayCreation(node As BoundArrayCreation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayLiteral(node As BoundArrayLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayInitialization(node As BoundArrayInitialization, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitFieldAccess(node As BoundFieldAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPropertyAccess(node As BoundPropertyAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitEventAccess(node As BoundEventAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBlock(node As BoundBlock, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitStateMachineScope(node As BoundStateMachineScope, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLocalDeclaration(node As BoundLocalDeclaration, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDimStatement(node As BoundDimStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInitializer(node As BoundInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitFieldInitializer(node As BoundFieldInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPropertyInitializer(node As BoundPropertyInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitParameterEqualsValue(node As BoundParameterEqualsValue, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequence(node As BoundSequence, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitExpressionStatement(node As BoundExpressionStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitIfStatement(node As BoundIfStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSelectStatement(node As BoundSelectStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCaseBlock(node As BoundCaseBlock, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCaseStatement(node As BoundCaseStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSimpleCaseClause(node As BoundSimpleCaseClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRangeCaseClause(node As BoundRangeCaseClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRelationalCaseClause(node As BoundRelationalCaseClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDoLoopStatement(node As BoundDoLoopStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWhileStatement(node As BoundWhileStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitForToStatement(node As BoundForToStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitForEachStatement(node As BoundForEachStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitExitStatement(node As BoundExitStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitContinueStatement(node As BoundContinueStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTryStatement(node As BoundTryStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCatchBlock(node As BoundCatchBlock, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLiteral(node As BoundLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMeReference(node As BoundMeReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitValueTypeMeReference(node As BoundValueTypeMeReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMyBaseReference(node As BoundMyBaseReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMyClassReference(node As BoundMyClassReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLocal(node As BoundLocal, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPseudoVariable(node As BoundPseudoVariable, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitParameter(node As BoundParameter, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLabelStatement(node As BoundLabelStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLabel(node As BoundLabel, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGotoStatement(node As BoundGotoStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitStatementList(node As BoundStatementList, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConditionalGoto(node As BoundConditionalGoto, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWithStatement(node As BoundWithStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnboundLambda(node As UnboundLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLambda(node As BoundLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryExpression(node As BoundQueryExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQuerySource(node As BoundQuerySource, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryableSource(node As BoundQueryableSource, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryClause(node As BoundQueryClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitOrdering(node As BoundOrdering, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryLambda(node As BoundQueryLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAggregateClause(node As BoundAggregateClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGroupAggregation(node As BoundGroupAggregation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRangeVariable(node As BoundRangeVariable, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAddHandlerStatement(node As BoundAddHandlerStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRaiseEventStatement(node As BoundRaiseEventStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUsingStatement(node As BoundUsingStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSyncLockStatement(node As BoundSyncLockStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlName(node As BoundXmlName, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlNamespace(node As BoundXmlNamespace, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlDocument(node As BoundXmlDocument, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlDeclaration(node As BoundXmlDeclaration, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlComment(node As BoundXmlComment, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlAttribute(node As BoundXmlAttribute, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlElement(node As BoundXmlElement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlMemberAccess(node As BoundXmlMemberAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlCData(node As BoundXmlCData, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitResumeStatement(node As BoundResumeStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitOnErrorStatement(node As BoundOnErrorStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAwaitOperator(node As BoundAwaitOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSpillSequence(node As BoundSpillSequence, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitStopStatement(node As BoundStopStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitEndStatement(node As BoundEndStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMidResult(node As BoundMidResult, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConditionalAccess(node As BoundConditionalAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNameOfOperator(node As BoundNameOfOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInterpolation(node As BoundInterpolation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
End Class
Friend MustInherit Partial Class BoundTreeVisitor
Public Overridable Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDup(node As BoundDup) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBadStatement(node As BoundBadStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayLength(node As BoundArrayLength) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGetType(node As BoundGetType) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeExpression(node As BoundTypeExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNamespaceExpression(node As BoundNamespaceExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMethodDefIndex(node As BoundMethodDefIndex) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitModuleVersionId(node As BoundModuleVersionId) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitModuleVersionIdString(node As BoundModuleVersionIdString) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConversion(node As BoundConversion) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRelaxationLambda(node As BoundRelaxationLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConvertedTupleElements(node As BoundConvertedTupleElements) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDirectCast(node As BoundDirectCast) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTryCast(node As BoundTryCast) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeOf(node As BoundTypeOf) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequencePointExpression(node As BoundSequencePointExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNoOpStatement(node As BoundNoOpStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRedimClause(node As BoundRedimClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitEraseStatement(node As BoundEraseStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCall(node As BoundCall) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAttribute(node As BoundAttribute) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNewT(node As BoundNewT) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitEventAccess(node As BoundEventAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBlock(node As BoundBlock) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitStateMachineScope(node As BoundStateMachineScope) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInitializer(node As BoundInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitParameterEqualsValue(node As BoundParameterEqualsValue) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequence(node As BoundSequence) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitIfStatement(node As BoundIfStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCaseStatement(node As BoundCaseStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSimpleCaseClause(node As BoundSimpleCaseClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRangeCaseClause(node As BoundRangeCaseClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRelationalCaseClause(node As BoundRelationalCaseClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDoLoopStatement(node As BoundDoLoopStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitForToStatement(node As BoundForToStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitExitStatement(node As BoundExitStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitContinueStatement(node As BoundContinueStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLiteral(node As BoundLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLocal(node As BoundLocal) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPseudoVariable(node As BoundPseudoVariable) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitParameter(node As BoundParameter) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLabel(node As BoundLabel) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitStatementList(node As BoundStatementList) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLambda(node As BoundLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQuerySource(node As BoundQuerySource) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryClause(node As BoundQueryClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitOrdering(node As BoundOrdering) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGroupAggregation(node As BoundGroupAggregation) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAddHandlerStatement(node As BoundAddHandlerStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlName(node As BoundXmlName) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitStopStatement(node As BoundStopStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitEndStatement(node As BoundEndStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMidResult(node As BoundMidResult) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNameOfOperator(node As BoundNameOfOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInterpolation(node As BoundInterpolation) As BoundNode
Return Me.DefaultVisit(node)
End Function
End Class
Friend MustInherit Partial Class BoundTreeWalker
Inherits BoundTreeVisitor
Public Overrides Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode
Me.Visit(node.UnderlyingLValue)
Return Nothing
End Function
Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitDup(node As BoundDup) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Me.VisitList(node.ChildBoundNodes)
Return Nothing
End Function
Public Overrides Function VisitBadStatement(node As BoundBadStatement) As BoundNode
Me.VisitList(node.ChildBoundNodes)
Return Nothing
End Function
Public Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
Me.Visit(node.Expression)
Me.VisitList(node.Indices)
Return Nothing
End Function
Public Overrides Function VisitArrayLength(node As BoundArrayLength) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitGetType(node As BoundGetType) As BoundNode
Me.Visit(node.SourceType)
Return Nothing
End Function
Public Overrides Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitTypeExpression(node As BoundTypeExpression) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitNamespaceExpression(node As BoundNamespaceExpression) As BoundNode
Me.Visit(node.UnevaluatedReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitMethodDefIndex(node As BoundMethodDefIndex) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitModuleVersionId(node As BoundModuleVersionId) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitModuleVersionIdString(node As BoundModuleVersionIdString) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
Me.Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Me.Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Me.Visit(node.Left)
Me.Visit(node.Right)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Me.Visit(node.LeftOperand)
Me.Visit(node.LeftOperandPlaceholder)
Me.Visit(node.LeftTest)
Me.Visit(node.BitwiseOperator)
Return Nothing
End Function
Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Me.Visit(node.Left)
Me.Visit(node.LeftOnTheRightOpt)
Me.Visit(node.Right)
Return Nothing
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
Me.Visit(node.ByRefLocal)
Me.Visit(node.LValue)
Return Nothing
End Function
Public Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Me.Visit(node.MethodGroup)
Return Nothing
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
Me.Visit(node.Condition)
Me.Visit(node.WhenTrue)
Me.Visit(node.WhenFalse)
Return Nothing
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
Me.Visit(node.TestExpression)
Me.Visit(node.ElseExpression)
Return Nothing
End Function
Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.ExtendedInfoOpt)
Return Nothing
End Function
Public Overrides Function VisitRelaxationLambda(node As BoundRelaxationLambda) As BoundNode
Me.Visit(node.Lambda)
Me.Visit(node.ReceiverPlaceholderOpt)
Return Nothing
End Function
Public Overrides Function VisitConvertedTupleElements(node As BoundConvertedTupleElements) As BoundNode
Me.VisitList(node.ElementPlaceholders)
Me.VisitList(node.ConvertedElements)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.RelaxationLambdaOpt)
Return Nothing
End Function
Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.RelaxationLambdaOpt)
Return Nothing
End Function
Public Overrides Function VisitTypeOf(node As BoundTypeOf) As BoundNode
Me.Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode
Me.Visit(node.StatementOpt)
Return Nothing
End Function
Public Overrides Function VisitSequencePointExpression(node As BoundSequencePointExpression) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode
Me.Visit(node.StatementOpt)
Return Nothing
End Function
Public Overrides Function VisitNoOpStatement(node As BoundNoOpStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Me.Visit(node.TypeArgumentsOpt)
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Me.Visit(node.ExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode
Me.Visit(node.ExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode
Me.VisitList(node.Clauses)
Return Nothing
End Function
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
Me.Visit(node.Operand)
Me.VisitList(node.Indices)
Return Nothing
End Function
Public Overrides Function VisitEraseStatement(node As BoundEraseStatement) As BoundNode
Me.VisitList(node.Clauses)
Return Nothing
End Function
Public Overrides Function VisitCall(node As BoundCall) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitAttribute(node As BoundAttribute) As BoundNode
Me.VisitList(node.ConstructorArguments)
Me.VisitList(node.NamedArguments)
Return Nothing
End Function
Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.Visit(node.TypeArgumentsOpt)
Return Nothing
End Function
Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Me.Visit(node.Member)
Me.VisitList(node.ArgumentsOpt)
Return Nothing
End Function
Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Me.Visit(node.MemberAccess)
Return Nothing
End Function
Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
Me.VisitList(node.Arguments)
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Me.VisitList(node.Declarations)
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Me.Visit(node.PlaceholderOpt)
Me.VisitList(node.Initializers)
Return Nothing
End Function
Public Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Me.Visit(node.PlaceholderOpt)
Me.VisitList(node.Initializers)
Return Nothing
End Function
Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.Visit(node.RelaxationLambdaOpt)
Me.Visit(node.RelaxationReceiverPlaceholderOpt)
Return Nothing
End Function
Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode
Me.VisitList(node.Bounds)
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Me.VisitList(node.Bounds)
Me.Visit(node.Initializer)
Return Nothing
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
Me.VisitList(node.Initializers)
Return Nothing
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitEventAccess(node As BoundEventAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Me.VisitList(node.Statements)
Return Nothing
End Function
Public Overrides Function VisitStateMachineScope(node As BoundStateMachineScope) As BoundNode
Me.Visit(node.Statement)
Return Nothing
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Me.Visit(node.DeclarationInitializerOpt)
Me.Visit(node.IdentifierInitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Me.VisitList(node.LocalDeclarations)
Me.Visit(node.Initializer)
Return Nothing
End Function
Public Overrides Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Me.VisitList(node.LocalDeclarations)
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitInitializer(node As BoundInitializer) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Me.Visit(node.MemberAccessExpressionOpt)
Me.Visit(node.InitialValue)
Return Nothing
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Me.Visit(node.MemberAccessExpressionOpt)
Me.Visit(node.InitialValue)
Return Nothing
End Function
Public Overrides Function VisitParameterEqualsValue(node As BoundParameterEqualsValue) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer) As BoundNode
Me.Visit(node.Statement)
Return Nothing
End Function
Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode
Me.VisitList(node.SideEffects)
Me.Visit(node.ValueOpt)
Return Nothing
End Function
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitIfStatement(node As BoundIfStatement) As BoundNode
Me.Visit(node.Condition)
Me.Visit(node.Consequence)
Me.Visit(node.AlternativeOpt)
Return Nothing
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Me.Visit(node.ExpressionStatement)
Me.Visit(node.ExprPlaceholderOpt)
Me.VisitList(node.CaseBlocks)
Return Nothing
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Me.Visit(node.CaseStatement)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitCaseStatement(node As BoundCaseStatement) As BoundNode
Me.VisitList(node.CaseClauses)
Me.Visit(node.ConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitSimpleCaseClause(node As BoundSimpleCaseClause) As BoundNode
Me.Visit(node.ValueOpt)
Me.Visit(node.ConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitRangeCaseClause(node As BoundRangeCaseClause) As BoundNode
Me.Visit(node.LowerBoundOpt)
Me.Visit(node.UpperBoundOpt)
Me.Visit(node.LowerBoundConditionOpt)
Me.Visit(node.UpperBoundConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitRelationalCaseClause(node As BoundRelationalCaseClause) As BoundNode
Me.Visit(node.ValueOpt)
Me.Visit(node.ConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitDoLoopStatement(node As BoundDoLoopStatement) As BoundNode
Me.Visit(node.TopConditionOpt)
Me.Visit(node.BottomConditionOpt)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Me.Visit(node.Condition)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators) As BoundNode
Me.Visit(node.LeftOperandPlaceholder)
Me.Visit(node.RightOperandPlaceholder)
Me.Visit(node.Addition)
Me.Visit(node.Subtraction)
Me.Visit(node.LessThanOrEqual)
Me.Visit(node.GreaterThanOrEqual)
Return Nothing
End Function
Public Overrides Function VisitForToStatement(node As BoundForToStatement) As BoundNode
Me.Visit(node.InitialValue)
Me.Visit(node.LimitValue)
Me.Visit(node.StepValue)
Me.Visit(node.OperatorsOpt)
Me.Visit(node.ControlVariable)
Me.Visit(node.Body)
Me.VisitList(node.NextVariablesOpt)
Return Nothing
End Function
Public Overrides Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
Me.Visit(node.Collection)
Me.Visit(node.ControlVariable)
Me.Visit(node.Body)
Me.VisitList(node.NextVariablesOpt)
Return Nothing
End Function
Public Overrides Function VisitExitStatement(node As BoundExitStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitContinueStatement(node As BoundContinueStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Me.Visit(node.TryBlock)
Me.VisitList(node.CatchBlocks)
Me.Visit(node.FinallyBlockOpt)
Return Nothing
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Me.Visit(node.ExceptionSourceOpt)
Me.Visit(node.ErrorLineNumberOpt)
Me.Visit(node.ExceptionFilterOpt)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitLiteral(node As BoundLiteral) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitPseudoVariable(node As BoundPseudoVariable) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Me.Visit(node.OriginalArgument)
Me.Visit(node.InConversion)
Me.Visit(node.InPlaceholder)
Me.Visit(node.OutConversion)
Me.Visit(node.OutPlaceholder)
Return Nothing
End Function
Public Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Me.Visit(node.OriginalArgument)
Return Nothing
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLabel(node As BoundLabel) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Me.Visit(node.LabelExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitStatementList(node As BoundStatementList) As BoundNode
Me.VisitList(node.Statements)
Return Nothing
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
Me.Visit(node.Condition)
Return Nothing
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Me.Visit(node.OriginalExpression)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
Me.Visit(node.LastOperator)
Return Nothing
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
Me.Visit(node.ConversionCall)
Return Nothing
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
Me.Visit(node.Source)
Return Nothing
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
Me.Visit(node.CapturedGroupOpt)
Me.Visit(node.GroupPlaceholderOpt)
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitGroupAggregation(node As BoundGroupAggregation) As BoundNode
Me.Visit(node.Group)
Return Nothing
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAddHandlerStatement(node As BoundAddHandlerStatement) As BoundNode
Me.Visit(node.EventAccess)
Me.Visit(node.Handler)
Return Nothing
End Function
Public Overrides Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement) As BoundNode
Me.Visit(node.EventAccess)
Me.Visit(node.Handler)
Return Nothing
End Function
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Me.Visit(node.EventInvocation)
Return Nothing
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Me.VisitList(node.ResourceList)
Me.Visit(node.ResourceExpressionOpt)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Me.Visit(node.LockExpression)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Me.Visit(node.XmlNamespace)
Me.Visit(node.LocalName)
Return Nothing
End Function
Public Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Me.Visit(node.XmlNamespace)
Return Nothing
End Function
Public Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Me.Visit(node.Declaration)
Me.VisitList(node.ChildNodes)
Return Nothing
End Function
Public Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Me.Visit(node.Version)
Me.Visit(node.Encoding)
Me.Visit(node.Standalone)
Return Nothing
End Function
Public Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Me.Visit(node.Target)
Me.Visit(node.Data)
Return Nothing
End Function
Public Overrides Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Me.Visit(node.Name)
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Me.Visit(node.Argument)
Me.VisitList(node.ChildNodes)
Return Nothing
End Function
Public Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Me.Visit(node.MemberAccess)
Return Nothing
End Function
Public Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
Me.Visit(node.LabelExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
Me.Visit(node.LabelExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement) As BoundNode
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter) As BoundNode
Me.Visit(node.ActiveHandlerLocal)
Me.Visit(node.ResumeTargetLocal)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode
Me.Visit(node.Value)
Me.VisitList(node.Jumps)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode
Me.Visit(node.ResumeTargetTemporary)
Me.Visit(node.ResumeLabel)
Me.Visit(node.ResumeNextLabel)
Me.VisitList(node.Jumps)
Return Nothing
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.AwaitableInstancePlaceholder)
Me.Visit(node.GetAwaiter)
Me.Visit(node.AwaiterInstancePlaceholder)
Me.Visit(node.IsCompleted)
Me.Visit(node.GetResult)
Return Nothing
End Function
Public Overrides Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode
Me.VisitList(node.Statements)
Me.Visit(node.ValueOpt)
Return Nothing
End Function
Public Overrides Function VisitStopStatement(node As BoundStopStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitEndStatement(node As BoundEndStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMidResult(node As BoundMidResult) As BoundNode
Me.Visit(node.Original)
Me.Visit(node.Start)
Me.Visit(node.LengthOpt)
Me.Visit(node.Source)
Return Nothing
End Function
Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode
Me.Visit(node.Receiver)
Me.Visit(node.Placeholder)
Me.Visit(node.AccessExpression)
Return Nothing
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
Me.Visit(node.ReceiverOrCondition)
Me.Visit(node.WhenNotNull)
Me.Visit(node.WhenNullOpt)
Return Nothing
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
Me.Visit(node.ValueTypeReceiver)
Me.Visit(node.ReferenceTypeReceiver)
Return Nothing
End Function
Public Overrides Function VisitNameOfOperator(node As BoundNameOfOperator) As BoundNode
Me.Visit(node.Argument)
Return Nothing
End Function
Public Overrides Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode
Me.VisitList(node.Contents)
Return Nothing
End Function
Public Overrides Function VisitInterpolation(node As BoundInterpolation) As BoundNode
Me.Visit(node.Expression)
Me.Visit(node.AlignmentOpt)
Me.Visit(node.FormatStringOpt)
Return Nothing
End Function
End Class
Friend MustInherit Partial Class BoundTreeRewriter
Inherits BoundTreeVisitor
Public Overrides Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Arguments)
End Function
Public Overrides Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode
Dim underlyingLValue As BoundExpression = DirectCast(Me.Visit(node.UnderlyingLValue), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingLValue, type)
End Function
Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitDup(node As BoundDup) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsReference, type)
End Function
Public Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Dim childBoundNodes As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ChildBoundNodes)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.ResultKind, node.Symbols, childBoundNodes, type)
End Function
Public Overrides Function VisitBadStatement(node As BoundBadStatement) As BoundNode
Dim childBoundNodes As ImmutableArray(Of BoundNode) = Me.VisitList(node.ChildBoundNodes)
Return node.Update(childBoundNodes)
End Function
Public Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, node.IsLValue, type)
End Function
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim indices As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Indices)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, indices, node.IsLValue, type)
End Function
Public Overrides Function VisitArrayLength(node As BoundArrayLength) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitGetType(node As BoundGetType) As BoundNode
Dim sourceType As BoundTypeExpression = DirectCast(Me.Visit(node.SourceType), BoundTypeExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(sourceType, type)
End Function
Public Overrides Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Field, type)
End Function
Public Overrides Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Method, type)
End Function
Public Overrides Function VisitTypeExpression(node As BoundTypeExpression) As BoundNode
Dim unevaluatedReceiverOpt As BoundExpression = node.UnevaluatedReceiverOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(unevaluatedReceiverOpt, node.AliasOpt, type)
End Function
Public Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Data, type)
End Function
Public Overrides Function VisitNamespaceExpression(node As BoundNamespaceExpression) As BoundNode
Dim unevaluatedReceiverOpt As BoundExpression = DirectCast(Me.Visit(node.UnevaluatedReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(unevaluatedReceiverOpt, node.AliasOpt, node.NamespaceSymbol)
End Function
Public Overrides Function VisitMethodDefIndex(node As BoundMethodDefIndex) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Method, type)
End Function
Public Overrides Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.AnalysisKind, node.IsLValue, type)
End Function
Public Overrides Function VisitModuleVersionId(node As BoundModuleVersionId) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsLValue, type)
End Function
Public Overrides Function VisitModuleVersionIdString(node As BoundModuleVersionIdString) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Document, type)
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, operand, node.Checked, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, underlyingExpression, type)
End Function
Public Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, type)
End Function
Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression)
Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, left, right, node.Checked, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, underlyingExpression, node.Checked, type)
End Function
Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Dim leftOperand As BoundExpression = DirectCast(Me.Visit(node.LeftOperand), BoundExpression)
Dim leftOperandPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.LeftOperandPlaceholder), BoundRValuePlaceholder)
Dim leftTest As BoundExpression = DirectCast(Me.Visit(node.LeftTest), BoundExpression)
Dim bitwiseOperator As BoundUserDefinedBinaryOperator = DirectCast(Me.Visit(node.BitwiseOperator), BoundUserDefinedBinaryOperator)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(leftOperand, leftOperandPlaceholder, leftTest, bitwiseOperator, type)
End Function
Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression)
Dim leftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder = DirectCast(Me.Visit(node.LeftOnTheRightOpt), BoundCompoundAssignmentTargetPlaceholder)
Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(left, leftOnTheRightOpt, right, node.SuppressObjectClone, type)
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
Dim byRefLocal As BoundLocal = DirectCast(Me.Visit(node.ByRefLocal), BoundLocal)
Dim lValue As BoundExpression = DirectCast(Me.Visit(node.LValue), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(byRefLocal, lValue, node.IsLValue, type)
End Function
Public Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Dim methodGroup As BoundMethodGroup = DirectCast(Me.Visit(node.MethodGroup), BoundMethodGroup)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.WithDependencies, methodGroup)
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Dim whenTrue As BoundExpression = DirectCast(Me.Visit(node.WhenTrue), BoundExpression)
Dim whenFalse As BoundExpression = DirectCast(Me.Visit(node.WhenFalse), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(condition, whenTrue, whenFalse, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
Dim testExpression As BoundExpression = DirectCast(Me.Visit(node.TestExpression), BoundExpression)
Dim convertedTestExpression As BoundExpression = node.ConvertedTestExpression
Dim testExpressionPlaceholder As BoundRValuePlaceholder = node.TestExpressionPlaceholder
Dim elseExpression As BoundExpression = DirectCast(Me.Visit(node.ElseExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(testExpression, convertedTestExpression, testExpressionPlaceholder, elseExpression, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim extendedInfoOpt As BoundExtendedConversionInfo = DirectCast(Me.Visit(node.ExtendedInfoOpt), BoundExtendedConversionInfo)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, extendedInfoOpt, type)
End Function
Public Overrides Function VisitRelaxationLambda(node As BoundRelaxationLambda) As BoundNode
Dim lambda As BoundLambda = DirectCast(Me.Visit(node.Lambda), BoundLambda)
Dim receiverPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.ReceiverPlaceholderOpt), BoundRValuePlaceholder)
Return node.Update(lambda, receiverPlaceholderOpt)
End Function
Public Overrides Function VisitConvertedTupleElements(node As BoundConvertedTupleElements) As BoundNode
Dim elementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder) = Me.VisitList(node.ElementPlaceholders)
Dim convertedElements As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ConvertedElements)
Return node.Update(elementPlaceholders, convertedElements)
End Function
Public Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingExpression, node.InOutConversionFlags, type)
End Function
Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim relaxationLambdaOpt As BoundLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.ConversionKind, node.SuppressVirtualCalls, node.ConstantValueOpt, relaxationLambdaOpt, type)
End Function
Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim relaxationLambdaOpt As BoundLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.ConversionKind, node.ConstantValueOpt, relaxationLambdaOpt, type)
End Function
Public Overrides Function VisitTypeOf(node As BoundTypeOf) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim targetType as TypeSymbol = Me.VisitType(node.TargetType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.IsTypeOfIsNotExpression, targetType, type)
End Function
Public Overrides Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode
Dim statementOpt As BoundStatement = DirectCast(Me.Visit(node.StatementOpt), BoundStatement)
Return node.Update(statementOpt)
End Function
Public Overrides Function VisitSequencePointExpression(node As BoundSequencePointExpression) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode
Dim statementOpt As BoundStatement = DirectCast(Me.Visit(node.StatementOpt), BoundStatement)
Return node.Update(statementOpt, node.Span)
End Function
Public Overrides Function VisitNoOpStatement(node As BoundNoOpStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Dim typeArgumentsOpt As BoundTypeArguments = DirectCast(Me.Visit(node.TypeArgumentsOpt), BoundTypeArguments)
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(typeArgumentsOpt, node.Methods, node.PendingExtensionMethodsOpt, node.ResultKind, receiverOpt, node.QualificationKind)
End Function
Public Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Properties, node.ResultKind, receiverOpt, node.QualificationKind)
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Dim expressionOpt As BoundExpression = DirectCast(Me.Visit(node.ExpressionOpt), BoundExpression)
Return node.Update(expressionOpt, node.FunctionLocalOpt, node.ExitLabelOpt)
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Return node.Update(expression)
End Function
Public Overrides Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode
Dim expressionOpt As BoundExpression = DirectCast(Me.Visit(node.ExpressionOpt), BoundExpression)
Return node.Update(expressionOpt)
End Function
Public Overrides Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode
Dim clauses As ImmutableArray(Of BoundRedimClause) = Me.VisitList(node.Clauses)
Return node.Update(clauses)
End Function
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim indices As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Indices)
Return node.Update(operand, indices, node.ArrayTypeOpt, node.Preserve)
End Function
Public Overrides Function VisitEraseStatement(node As BoundEraseStatement) As BoundNode
Dim clauses As ImmutableArray(Of BoundAssignmentOperator) = Me.VisitList(node.Clauses)
Return node.Update(clauses)
End Function
Public Overrides Function VisitCall(node As BoundCall) As BoundNode
Dim methodGroupOpt As BoundMethodGroup = node.MethodGroupOpt
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Method, methodGroupOpt, receiverOpt, arguments, node.DefaultArguments, node.ConstantValueOpt, node.IsLValue, node.SuppressObjectClone, type)
End Function
Public Overrides Function VisitAttribute(node As BoundAttribute) As BoundNode
Dim constructorArguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ConstructorArguments)
Dim namedArguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.NamedArguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Constructor, constructorArguments, namedArguments, node.ResultKind, type)
End Function
Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim typeArgumentsOpt As BoundTypeArguments = DirectCast(Me.Visit(node.TypeArgumentsOpt), BoundTypeArguments)
Dim containerTypeOpt as TypeSymbol = Me.VisitType(node.ContainerTypeOpt)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.NameOpt, containerTypeOpt, receiverOpt, typeArgumentsOpt, node.AccessKind, type)
End Function
Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Dim member As BoundExpression = DirectCast(Me.Visit(node.Member), BoundExpression)
Dim argumentsOpt As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ArgumentsOpt)
Dim methodOrPropertyGroupOpt As BoundMethodOrPropertyGroup = node.MethodOrPropertyGroupOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(member, argumentsOpt, node.ArgumentNamesOpt, node.AccessKind, methodOrPropertyGroupOpt, type)
End Function
Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Dim memberAccess As BoundLateMemberAccess = DirectCast(Me.Visit(node.MemberAccess), BoundLateMemberAccess)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, memberAccess, type)
End Function
Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.InferredType, node.ArgumentNamesOpt, node.InferredNamesOpt, arguments, type)
End Function
Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim naturalTypeOpt as TypeSymbol = Me.VisitType(node.NaturalTypeOpt)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(naturalTypeOpt, arguments, type)
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
Dim methodGroupOpt As BoundMethodGroup = node.MethodGroupOpt
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim initializerOpt As BoundObjectInitializerExpressionBase = DirectCast(Me.Visit(node.InitializerOpt), BoundObjectInitializerExpressionBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.ConstructorOpt, methodGroupOpt, arguments, node.DefaultArguments, initializerOpt, type)
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
Dim initializerOpt As BoundObjectInitializerExpressionBase = DirectCast(Me.Visit(node.InitializerOpt), BoundObjectInitializerExpressionBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.GuidString, initializerOpt, type)
End Function
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Dim declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess) = Me.VisitList(node.Declarations)
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.BinderOpt, declarations, arguments, type)
End Function
Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.PropertyIndex, type)
End Function
Public Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, value, type)
End Function
Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Dim placeholderOpt As BoundWithLValueExpressionPlaceholder = DirectCast(Me.Visit(node.PlaceholderOpt), BoundWithLValueExpressionPlaceholder)
Dim initializers As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Initializers)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.CreateTemporaryLocalForInitialization, placeholderOpt, initializers, type)
End Function
Public Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Dim placeholderOpt As BoundWithLValueExpressionPlaceholder = DirectCast(Me.Visit(node.PlaceholderOpt), BoundWithLValueExpressionPlaceholder)
Dim initializers As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Initializers)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(placeholderOpt, initializers, type)
End Function
Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Dim initializerOpt As BoundObjectInitializerExpressionBase = DirectCast(Me.Visit(node.InitializerOpt), BoundObjectInitializerExpressionBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(initializerOpt, type)
End Function
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim relaxationLambdaOpt As BoundLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda)
Dim relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.RelaxationReceiverPlaceholderOpt), BoundRValuePlaceholder)
Dim methodGroupOpt As BoundMethodGroup = node.MethodGroupOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOpt, node.Method, relaxationLambdaOpt, relaxationReceiverPlaceholderOpt, methodGroupOpt, type)
End Function
Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode
Dim bounds As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Bounds)
Dim initializerOpt As BoundArrayInitialization = DirectCast(Me.Visit(node.InitializerOpt), BoundArrayInitialization)
Dim arrayLiteralOpt As BoundArrayLiteral = node.ArrayLiteralOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsParamArrayArgument, bounds, initializerOpt, arrayLiteralOpt, node.ArrayLiteralConversion, type)
End Function
Public Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Dim bounds As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Bounds)
Dim initializer As BoundArrayInitialization = DirectCast(Me.Visit(node.Initializer), BoundArrayInitialization)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.HasDominantType, node.NumberOfCandidates, node.InferredType, bounds, initializer, node.Binder)
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
Dim initializers As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Initializers)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(initializers, type)
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOpt, node.FieldSymbol, node.IsLValue, node.SuppressVirtualCalls, node.ConstantsInProgressOpt, type)
End Function
Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Dim propertyGroupOpt As BoundPropertyGroup = node.PropertyGroupOpt
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.PropertySymbol, propertyGroupOpt, node.AccessKind, node.IsWriteable, node.IsLValue, receiverOpt, arguments, node.DefaultArguments, type)
End Function
Public Overrides Function VisitEventAccess(node As BoundEventAccess) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOpt, node.EventSymbol, type)
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Dim statements As ImmutableArray(Of BoundStatement) = Me.VisitList(node.Statements)
Return node.Update(node.StatementListSyntax, node.Locals, statements)
End Function
Public Overrides Function VisitStateMachineScope(node As BoundStateMachineScope) As BoundNode
Dim statement As BoundStatement = DirectCast(Me.Visit(node.Statement), BoundStatement)
Return node.Update(node.Fields, statement)
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Dim declarationInitializerOpt As BoundExpression = DirectCast(Me.Visit(node.DeclarationInitializerOpt), BoundExpression)
Dim identifierInitializerOpt As BoundArrayCreation = DirectCast(Me.Visit(node.IdentifierInitializerOpt), BoundArrayCreation)
Return node.Update(node.LocalSymbol, declarationInitializerOpt, identifierInitializerOpt, node.InitializedByAsNew)
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Dim localDeclarations As ImmutableArray(Of BoundLocalDeclaration) = Me.VisitList(node.LocalDeclarations)
Dim initializer As BoundExpression = DirectCast(Me.Visit(node.Initializer), BoundExpression)
Return node.Update(localDeclarations, initializer, node.Binder)
End Function
Public Overrides Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Dim localDeclarations As ImmutableArray(Of BoundLocalDeclarationBase) = Me.VisitList(node.LocalDeclarations)
Dim initializerOpt As BoundExpression = DirectCast(Me.Visit(node.InitializerOpt), BoundExpression)
Return node.Update(localDeclarations, initializerOpt)
End Function
Public Overrides Function VisitInitializer(node As BoundInitializer) As BoundNode
Return node
End Function
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Dim memberAccessExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.MemberAccessExpressionOpt), BoundExpression)
Dim initialValue As BoundExpression = DirectCast(Me.Visit(node.InitialValue), BoundExpression)
Return node.Update(node.InitializedFields, memberAccessExpressionOpt, initialValue, node.BinderOpt)
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Dim memberAccessExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.MemberAccessExpressionOpt), BoundExpression)
Dim initialValue As BoundExpression = DirectCast(Me.Visit(node.InitialValue), BoundExpression)
Return node.Update(node.InitializedProperties, memberAccessExpressionOpt, initialValue, node.BinderOpt)
End Function
Public Overrides Function VisitParameterEqualsValue(node As BoundParameterEqualsValue) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Return node.Update(node.Parameter, value)
End Function
Public Overrides Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer) As BoundNode
Dim statement As BoundStatement = DirectCast(Me.Visit(node.Statement), BoundStatement)
Return node.Update(statement)
End Function
Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode
Dim sideEffects As ImmutableArray(Of BoundExpression) = Me.VisitList(node.SideEffects)
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Locals, sideEffects, valueOpt, type)
End Function
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Return node.Update(expression)
End Function
Public Overrides Function VisitIfStatement(node As BoundIfStatement) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Dim consequence As BoundStatement = DirectCast(Me.Visit(node.Consequence), BoundStatement)
Dim alternativeOpt As BoundStatement = DirectCast(Me.Visit(node.AlternativeOpt), BoundStatement)
Return node.Update(condition, consequence, alternativeOpt)
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Dim expressionStatement As BoundExpressionStatement = DirectCast(Me.Visit(node.ExpressionStatement), BoundExpressionStatement)
Dim exprPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.ExprPlaceholderOpt), BoundRValuePlaceholder)
Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = Me.VisitList(node.CaseBlocks)
Return node.Update(expressionStatement, exprPlaceholderOpt, caseBlocks, node.RecommendSwitchTable, node.ExitLabel)
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Dim caseStatement As BoundCaseStatement = DirectCast(Me.Visit(node.CaseStatement), BoundCaseStatement)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(caseStatement, body)
End Function
Public Overrides Function VisitCaseStatement(node As BoundCaseStatement) As BoundNode
Dim caseClauses As ImmutableArray(Of BoundCaseClause) = Me.VisitList(node.CaseClauses)
Dim conditionOpt As BoundExpression = DirectCast(Me.Visit(node.ConditionOpt), BoundExpression)
Return node.Update(caseClauses, conditionOpt)
End Function
Public Overrides Function VisitSimpleCaseClause(node As BoundSimpleCaseClause) As BoundNode
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim conditionOpt As BoundExpression = DirectCast(Me.Visit(node.ConditionOpt), BoundExpression)
Return node.Update(valueOpt, conditionOpt)
End Function
Public Overrides Function VisitRangeCaseClause(node As BoundRangeCaseClause) As BoundNode
Dim lowerBoundOpt As BoundExpression = DirectCast(Me.Visit(node.LowerBoundOpt), BoundExpression)
Dim upperBoundOpt As BoundExpression = DirectCast(Me.Visit(node.UpperBoundOpt), BoundExpression)
Dim lowerBoundConditionOpt As BoundExpression = DirectCast(Me.Visit(node.LowerBoundConditionOpt), BoundExpression)
Dim upperBoundConditionOpt As BoundExpression = DirectCast(Me.Visit(node.UpperBoundConditionOpt), BoundExpression)
Return node.Update(lowerBoundOpt, upperBoundOpt, lowerBoundConditionOpt, upperBoundConditionOpt)
End Function
Public Overrides Function VisitRelationalCaseClause(node As BoundRelationalCaseClause) As BoundNode
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim conditionOpt As BoundExpression = DirectCast(Me.Visit(node.ConditionOpt), BoundExpression)
Return node.Update(node.OperatorKind, valueOpt, conditionOpt)
End Function
Public Overrides Function VisitDoLoopStatement(node As BoundDoLoopStatement) As BoundNode
Dim topConditionOpt As BoundExpression = DirectCast(Me.Visit(node.TopConditionOpt), BoundExpression)
Dim bottomConditionOpt As BoundExpression = DirectCast(Me.Visit(node.BottomConditionOpt), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Return node.Update(topConditionOpt, bottomConditionOpt, node.TopConditionIsUntil, node.BottomConditionIsUntil, body, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Return node.Update(condition, body, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators) As BoundNode
Dim leftOperandPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.LeftOperandPlaceholder), BoundRValuePlaceholder)
Dim rightOperandPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.RightOperandPlaceholder), BoundRValuePlaceholder)
Dim addition As BoundUserDefinedBinaryOperator = DirectCast(Me.Visit(node.Addition), BoundUserDefinedBinaryOperator)
Dim subtraction As BoundUserDefinedBinaryOperator = DirectCast(Me.Visit(node.Subtraction), BoundUserDefinedBinaryOperator)
Dim lessThanOrEqual As BoundExpression = DirectCast(Me.Visit(node.LessThanOrEqual), BoundExpression)
Dim greaterThanOrEqual As BoundExpression = DirectCast(Me.Visit(node.GreaterThanOrEqual), BoundExpression)
Return node.Update(leftOperandPlaceholder, rightOperandPlaceholder, addition, subtraction, lessThanOrEqual, greaterThanOrEqual)
End Function
Public Overrides Function VisitForToStatement(node As BoundForToStatement) As BoundNode
Dim initialValue As BoundExpression = DirectCast(Me.Visit(node.InitialValue), BoundExpression)
Dim limitValue As BoundExpression = DirectCast(Me.Visit(node.LimitValue), BoundExpression)
Dim stepValue As BoundExpression = DirectCast(Me.Visit(node.StepValue), BoundExpression)
Dim operatorsOpt As BoundForToUserDefinedOperators = DirectCast(Me.Visit(node.OperatorsOpt), BoundForToUserDefinedOperators)
Dim controlVariable As BoundExpression = DirectCast(Me.Visit(node.ControlVariable), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Dim nextVariablesOpt As ImmutableArray(Of BoundExpression) = Me.VisitList(node.NextVariablesOpt)
Return node.Update(initialValue, limitValue, stepValue, node.Checked, operatorsOpt, node.DeclaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
Dim collection As BoundExpression = DirectCast(Me.Visit(node.Collection), BoundExpression)
Dim controlVariable As BoundExpression = DirectCast(Me.Visit(node.ControlVariable), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Dim nextVariablesOpt As ImmutableArray(Of BoundExpression) = Me.VisitList(node.NextVariablesOpt)
Return node.Update(collection, node.EnumeratorInfo, node.DeclaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitExitStatement(node As BoundExitStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitContinueStatement(node As BoundContinueStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Dim tryBlock As BoundBlock = DirectCast(Me.Visit(node.TryBlock), BoundBlock)
Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks)
Dim finallyBlockOpt As BoundBlock = DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock)
Return node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.ExitLabelOpt)
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Dim exceptionSourceOpt As BoundExpression = DirectCast(Me.Visit(node.ExceptionSourceOpt), BoundExpression)
Dim errorLineNumberOpt As BoundExpression = DirectCast(Me.Visit(node.ErrorLineNumberOpt), BoundExpression)
Dim exceptionFilterOpt As BoundExpression = DirectCast(Me.Visit(node.ExceptionFilterOpt), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(node.LocalOpt, exceptionSourceOpt, errorLineNumberOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll)
End Function
Public Overrides Function VisitLiteral(node As BoundLiteral) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Value, type)
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.SourceType, type)
End Function
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LocalSymbol, node.IsLValue, type)
End Function
Public Overrides Function VisitPseudoVariable(node As BoundPseudoVariable) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LocalSymbol, node.IsLValue, node.EmitExpressions, type)
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.ParameterSymbol, node.IsLValue, node.SuppressVirtualCalls, type)
End Function
Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsOut, type)
End Function
Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Dim originalArgument As BoundExpression = DirectCast(Me.Visit(node.OriginalArgument), BoundExpression)
Dim inConversion As BoundExpression = DirectCast(Me.Visit(node.InConversion), BoundExpression)
Dim inPlaceholder As BoundByRefArgumentPlaceholder = DirectCast(Me.Visit(node.InPlaceholder), BoundByRefArgumentPlaceholder)
Dim outConversion As BoundExpression = DirectCast(Me.Visit(node.OutConversion), BoundExpression)
Dim outPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.OutPlaceholder), BoundRValuePlaceholder)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(originalArgument, inConversion, inPlaceholder, outConversion, outPlaceholder, type)
End Function
Public Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Dim originalArgument As BoundExpression = DirectCast(Me.Visit(node.OriginalArgument), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(originalArgument, node.LocalSymbol, type)
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitLabel(node As BoundLabel) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Label, type)
End Function
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Dim labelExpressionOpt As BoundLabel = DirectCast(Me.Visit(node.LabelExpressionOpt), BoundLabel)
Return node.Update(node.Label, labelExpressionOpt)
End Function
Public Overrides Function VisitStatementList(node As BoundStatementList) As BoundNode
Dim statements As ImmutableArray(Of BoundStatement) = Me.VisitList(node.Statements)
Return node.Update(statements)
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Return node.Update(condition, node.JumpIfTrue, node.Label)
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Dim originalExpression As BoundExpression = DirectCast(Me.Visit(node.OriginalExpression), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(originalExpression, body, node.Binder)
End Function
Public Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Dim returnType as TypeSymbol = Me.VisitType(node.ReturnType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.Flags, node.Parameters, returnType, node.BindingCache)
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LambdaSymbol, body, node.Diagnostics, node.LambdaBinderOpt, node.DelegateRelaxation, node.MethodConversionKind)
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
Dim lastOperator As BoundQueryClauseBase = DirectCast(Me.Visit(node.LastOperator), BoundQueryClauseBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(lastOperator, type)
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
Dim conversionCall As BoundCall = DirectCast(Me.Visit(node.ConversionCall), BoundCall)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(conversionCall, type)
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
Dim source As BoundQueryPart = DirectCast(Me.Visit(node.Source), BoundQueryPart)
Dim compoundVariableType as TypeSymbol = Me.VisitType(node.CompoundVariableType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(source, node.RangeVariableOpt, node.RangeVariables, compoundVariableType, node.Binders, type)
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim compoundVariableType as TypeSymbol = Me.VisitType(node.CompoundVariableType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingExpression, node.RangeVariables, compoundVariableType, node.Binders, type)
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingExpression, type)
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LambdaSymbol, node.RangeVariables, expression, node.ExprIsOperandOfConditionalBranch)
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.RangeVariable, value, type)
End Function
Public Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.Parameters, node.Compilation)
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
Dim capturedGroupOpt As BoundQueryClauseBase = DirectCast(Me.Visit(node.CapturedGroupOpt), BoundQueryClauseBase)
Dim groupPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.GroupPlaceholderOpt), BoundRValuePlaceholder)
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim compoundVariableType as TypeSymbol = Me.VisitType(node.CompoundVariableType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(capturedGroupOpt, groupPlaceholderOpt, underlyingExpression, node.RangeVariables, compoundVariableType, node.Binders, type)
End Function
Public Overrides Function VisitGroupAggregation(node As BoundGroupAggregation) As BoundNode
Dim group As BoundExpression = DirectCast(Me.Visit(node.Group), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(group, type)
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.RangeVariable, type)
End Function
Public Overrides Function VisitAddHandlerStatement(node As BoundAddHandlerStatement) As BoundNode
Dim eventAccess As BoundExpression = DirectCast(Me.Visit(node.EventAccess), BoundExpression)
Dim handler As BoundExpression = DirectCast(Me.Visit(node.Handler), BoundExpression)
Return node.Update(eventAccess, handler)
End Function
Public Overrides Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement) As BoundNode
Dim eventAccess As BoundExpression = DirectCast(Me.Visit(node.EventAccess), BoundExpression)
Dim handler As BoundExpression = DirectCast(Me.Visit(node.Handler), BoundExpression)
Return node.Update(eventAccess, handler)
End Function
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Dim eventInvocation As BoundExpression = DirectCast(Me.Visit(node.EventInvocation), BoundExpression)
Return node.Update(node.EventSymbol, eventInvocation)
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Dim resourceList As ImmutableArray(Of BoundLocalDeclarationBase) = Me.VisitList(node.ResourceList)
Dim resourceExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.ResourceExpressionOpt), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(resourceList, resourceExpressionOpt, body, node.UsingInfo, node.Locals)
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Dim lockExpression As BoundExpression = DirectCast(Me.Visit(node.LockExpression), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(lockExpression, body)
End Function
Public Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Dim xmlNamespace As BoundExpression = DirectCast(Me.Visit(node.XmlNamespace), BoundExpression)
Dim localName As BoundExpression = DirectCast(Me.Visit(node.LocalName), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(xmlNamespace, localName, objectCreation, type)
End Function
Public Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Dim xmlNamespace As BoundExpression = DirectCast(Me.Visit(node.XmlNamespace), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(xmlNamespace, objectCreation, type)
End Function
Public Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Dim declaration As BoundExpression = DirectCast(Me.Visit(node.Declaration), BoundExpression)
Dim childNodes As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ChildNodes)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(declaration, childNodes, node.RewriterInfo, type)
End Function
Public Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Dim version As BoundExpression = DirectCast(Me.Visit(node.Version), BoundExpression)
Dim encoding As BoundExpression = DirectCast(Me.Visit(node.Encoding), BoundExpression)
Dim standalone As BoundExpression = DirectCast(Me.Visit(node.Standalone), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(version, encoding, standalone, objectCreation, type)
End Function
Public Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Dim target As BoundExpression = DirectCast(Me.Visit(node.Target), BoundExpression)
Dim data As BoundExpression = DirectCast(Me.Visit(node.Data), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(target, data, objectCreation, type)
End Function
Public Overrides Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(value, objectCreation, type)
End Function
Public Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Dim name As BoundExpression = DirectCast(Me.Visit(node.Name), BoundExpression)
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(name, value, node.MatchesImport, objectCreation, type)
End Function
Public Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Dim argument As BoundExpression = DirectCast(Me.Visit(node.Argument), BoundExpression)
Dim childNodes As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ChildNodes)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(argument, childNodes, node.RewriterInfo, type)
End Function
Public Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Dim memberAccess As BoundExpression = DirectCast(Me.Visit(node.MemberAccess), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(memberAccess, type)
End Function
Public Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Dim value As BoundLiteral = DirectCast(Me.Visit(node.Value), BoundLiteral)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(value, objectCreation, type)
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
Dim labelExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.LabelExpressionOpt), BoundExpression)
Return node.Update(node.ResumeKind, node.LabelOpt, labelExpressionOpt)
End Function
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
Dim labelExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.LabelExpressionOpt), BoundExpression)
Return node.Update(node.OnErrorKind, node.LabelOpt, labelExpressionOpt)
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement) As BoundNode
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(node.ContainsOnError, node.ContainsResume, node.ResumeWithoutLabelOpt, node.TrackLineNumber, body)
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter) As BoundNode
Dim activeHandlerLocal As BoundLocal = DirectCast(Me.Visit(node.ActiveHandlerLocal), BoundLocal)
Dim resumeTargetLocal As BoundLocal = DirectCast(Me.Visit(node.ResumeTargetLocal), BoundLocal)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(activeHandlerLocal, resumeTargetLocal, type)
End Function
Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim jumps As ImmutableArray(Of BoundGotoStatement) = Me.VisitList(node.Jumps)
Return node.Update(value, jumps)
End Function
Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode
Dim resumeTargetTemporary As BoundLocal = DirectCast(Me.Visit(node.ResumeTargetTemporary), BoundLocal)
Dim resumeLabel As BoundLabelStatement = DirectCast(Me.Visit(node.ResumeLabel), BoundLabelStatement)
Dim resumeNextLabel As BoundLabelStatement = DirectCast(Me.Visit(node.ResumeNextLabel), BoundLabelStatement)
Dim jumps As ImmutableArray(Of BoundGotoStatement) = Me.VisitList(node.Jumps)
Return node.Update(resumeTargetTemporary, resumeLabel, resumeNextLabel, jumps)
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim awaitableInstancePlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.AwaitableInstancePlaceholder), BoundRValuePlaceholder)
Dim getAwaiter As BoundExpression = DirectCast(Me.Visit(node.GetAwaiter), BoundExpression)
Dim awaiterInstancePlaceholder As BoundLValuePlaceholder = DirectCast(Me.Visit(node.AwaiterInstancePlaceholder), BoundLValuePlaceholder)
Dim isCompleted As BoundExpression = DirectCast(Me.Visit(node.IsCompleted), BoundExpression)
Dim getResult As BoundExpression = DirectCast(Me.Visit(node.GetResult), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, awaitableInstancePlaceholder, getAwaiter, awaiterInstancePlaceholder, isCompleted, getResult, type)
End Function
Public Overrides Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode
Dim statements As ImmutableArray(Of BoundStatement) = Me.VisitList(node.Statements)
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Locals, node.SpillFields, statements, valueOpt, type)
End Function
Public Overrides Function VisitStopStatement(node As BoundStopStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitEndStatement(node As BoundEndStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitMidResult(node As BoundMidResult) As BoundNode
Dim original As BoundExpression = DirectCast(Me.Visit(node.Original), BoundExpression)
Dim start As BoundExpression = DirectCast(Me.Visit(node.Start), BoundExpression)
Dim lengthOpt As BoundExpression = DirectCast(Me.Visit(node.LengthOpt), BoundExpression)
Dim source As BoundExpression = DirectCast(Me.Visit(node.Source), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(original, start, lengthOpt, source, type)
End Function
Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode
Dim receiver As BoundExpression = DirectCast(Me.Visit(node.Receiver), BoundExpression)
Dim placeholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.Placeholder), BoundRValuePlaceholder)
Dim accessExpression As BoundExpression = DirectCast(Me.Visit(node.AccessExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiver, placeholder, accessExpression, type)
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.PlaceholderId, type)
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
Dim receiverOrCondition As BoundExpression = DirectCast(Me.Visit(node.ReceiverOrCondition), BoundExpression)
Dim whenNotNull As BoundExpression = DirectCast(Me.Visit(node.WhenNotNull), BoundExpression)
Dim whenNullOpt As BoundExpression = DirectCast(Me.Visit(node.WhenNullOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOrCondition, node.CaptureReceiver, node.PlaceholderId, whenNotNull, whenNullOpt, type)
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
Dim valueTypeReceiver As BoundExpression = DirectCast(Me.Visit(node.ValueTypeReceiver), BoundExpression)
Dim referenceTypeReceiver As BoundExpression = DirectCast(Me.Visit(node.ReferenceTypeReceiver), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(valueTypeReceiver, referenceTypeReceiver, type)
End Function
Public Overrides Function VisitNameOfOperator(node As BoundNameOfOperator) As BoundNode
Dim argument As BoundExpression = DirectCast(Me.Visit(node.Argument), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(argument, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression) As BoundNode
Dim expression As BoundTypeExpression = DirectCast(Me.Visit(node.Expression), BoundTypeExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode
Dim contents As ImmutableArray(Of BoundNode) = Me.VisitList(node.Contents)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(contents, node.Binder, type)
End Function
Public Overrides Function VisitInterpolation(node As BoundInterpolation) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim alignmentOpt As BoundExpression = DirectCast(Me.Visit(node.AlignmentOpt), BoundExpression)
Dim formatStringOpt As BoundLiteral = DirectCast(Me.Visit(node.FormatStringOpt), BoundLiteral)
Return node.Update(expression, alignmentOpt, formatStringOpt)
End Function
End Class
Friend NotInheritable Class BoundTreeDumperNodeProducer
Inherits BoundTreeVisitor(Of Object, TreeDumperNode)
Private Sub New()
End Sub
Public Shared Function MakeTree(node As BoundNode) As TreeDumperNode
Return (New BoundTreeDumperNodeProducer()).Visit(node, Nothing)
End Function
Public Overrides Function VisitTypeArguments(node As BoundTypeArguments, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeArguments", Nothing, New TreeDumperNode() {
New TreeDumperNode("arguments", node.Arguments, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitOmittedArgument(node As BoundOmittedArgument, arg As Object) As TreeDumperNode
Return New TreeDumperNode("omittedArgument", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lValueToRValueWrapper", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingLValue", Nothing, new TreeDumperNode() {Visit(node.UnderlyingLValue, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("withLValueExpressionPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("withRValueExpressionPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rValuePlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lValuePlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitDup(node As BoundDup, arg As Object) As TreeDumperNode
Return New TreeDumperNode("dup", Nothing, New TreeDumperNode() {
New TreeDumperNode("isReference", node.IsReference, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBadExpression(node As BoundBadExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("badExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("symbols", node.Symbols, Nothing),
New TreeDumperNode("childBoundNodes", Nothing, From x In node.ChildBoundNodes Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBadStatement(node As BoundBadStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("badStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("childBoundNodes", Nothing, From x In node.ChildBoundNodes Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitParenthesized(node As BoundParenthesized, arg As Object) As TreeDumperNode
Return New TreeDumperNode("parenthesized", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBadVariable(node As BoundBadVariable, arg As Object) As TreeDumperNode
Return New TreeDumperNode("badVariable", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("indices", Nothing, From x In node.Indices Select Visit(x, Nothing)),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayLength(node As BoundArrayLength, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayLength", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGetType(node As BoundGetType, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[getType]", Nothing, New TreeDumperNode() {
New TreeDumperNode("sourceType", Nothing, new TreeDumperNode() {Visit(node.SourceType, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitFieldInfo(node As BoundFieldInfo, arg As Object) As TreeDumperNode
Return New TreeDumperNode("fieldInfo", Nothing, New TreeDumperNode() {
New TreeDumperNode("field", node.Field, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMethodInfo(node As BoundMethodInfo, arg As Object) As TreeDumperNode
Return New TreeDumperNode("methodInfo", Nothing, New TreeDumperNode() {
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeExpression(node As BoundTypeExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("unevaluatedReceiverOpt", Nothing, new TreeDumperNode() {Visit(node.UnevaluatedReceiverOpt, Nothing)}),
New TreeDumperNode("aliasOpt", node.AliasOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeOrValueExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("data", node.Data, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNamespaceExpression(node As BoundNamespaceExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("namespaceExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("unevaluatedReceiverOpt", Nothing, new TreeDumperNode() {Visit(node.UnevaluatedReceiverOpt, Nothing)}),
New TreeDumperNode("aliasOpt", node.AliasOpt, Nothing),
New TreeDumperNode("namespaceSymbol", node.NamespaceSymbol, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMethodDefIndex(node As BoundMethodDefIndex, arg As Object) As TreeDumperNode
Return New TreeDumperNode("methodDefIndex", Nothing, New TreeDumperNode() {
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex, arg As Object) As TreeDumperNode
Return New TreeDumperNode("maximumMethodDefIndex", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot, arg As Object) As TreeDumperNode
Return New TreeDumperNode("instrumentationPayloadRoot", Nothing, New TreeDumperNode() {
New TreeDumperNode("analysisKind", node.AnalysisKind, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitModuleVersionId(node As BoundModuleVersionId, arg As Object) As TreeDumperNode
Return New TreeDumperNode("moduleVersionId", Nothing, New TreeDumperNode() {
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitModuleVersionIdString(node As BoundModuleVersionIdString, arg As Object) As TreeDumperNode
Return New TreeDumperNode("moduleVersionIdString", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sourceDocumentIndex", Nothing, New TreeDumperNode() {
New TreeDumperNode("document", node.Document, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedUnaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("nullableIsTrueOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("binaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("left", Nothing, new TreeDumperNode() {Visit(node.Left, Nothing)}),
New TreeDumperNode("right", Nothing, new TreeDumperNode() {Visit(node.Right, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedBinaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedShortCircuitingOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("leftOperand", Nothing, new TreeDumperNode() {Visit(node.LeftOperand, Nothing)}),
New TreeDumperNode("leftOperandPlaceholder", Nothing, new TreeDumperNode() {Visit(node.LeftOperandPlaceholder, Nothing)}),
New TreeDumperNode("leftTest", Nothing, new TreeDumperNode() {Visit(node.LeftTest, Nothing)}),
New TreeDumperNode("bitwiseOperator", Nothing, new TreeDumperNode() {Visit(node.BitwiseOperator, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("compoundAssignmentTargetPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("assignmentOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("left", Nothing, new TreeDumperNode() {Visit(node.Left, Nothing)}),
New TreeDumperNode("leftOnTheRightOpt", Nothing, new TreeDumperNode() {Visit(node.LeftOnTheRightOpt, Nothing)}),
New TreeDumperNode("right", Nothing, new TreeDumperNode() {Visit(node.Right, Nothing)}),
New TreeDumperNode("suppressObjectClone", node.SuppressObjectClone, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment, arg As Object) As TreeDumperNode
Return New TreeDumperNode("referenceAssignment", Nothing, New TreeDumperNode() {
New TreeDumperNode("byRefLocal", Nothing, new TreeDumperNode() {Visit(node.ByRefLocal, Nothing)}),
New TreeDumperNode("lValue", Nothing, new TreeDumperNode() {Visit(node.LValue, Nothing)}),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("addressOfOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("withDependencies", node.WithDependencies, Nothing),
New TreeDumperNode("methodGroup", Nothing, new TreeDumperNode() {Visit(node.MethodGroup, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("ternaryConditionalExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("whenTrue", Nothing, new TreeDumperNode() {Visit(node.WhenTrue, Nothing)}),
New TreeDumperNode("whenFalse", Nothing, new TreeDumperNode() {Visit(node.WhenFalse, Nothing)}),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("binaryConditionalExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("testExpression", Nothing, new TreeDumperNode() {Visit(node.TestExpression, Nothing)}),
New TreeDumperNode("convertedTestExpression", Nothing, new TreeDumperNode() {Visit(node.ConvertedTestExpression, Nothing)}),
New TreeDumperNode("testExpressionPlaceholder", Nothing, new TreeDumperNode() {Visit(node.TestExpressionPlaceholder, Nothing)}),
New TreeDumperNode("elseExpression", Nothing, new TreeDumperNode() {Visit(node.ElseExpression, Nothing)}),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConversion(node As BoundConversion, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conversion", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("conversionKind", node.ConversionKind, Nothing),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("explicitCastInCode", node.ExplicitCastInCode, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("extendedInfoOpt", Nothing, new TreeDumperNode() {Visit(node.ExtendedInfoOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRelaxationLambda(node As BoundRelaxationLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("relaxationLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("lambda", Nothing, new TreeDumperNode() {Visit(node.Lambda, Nothing)}),
New TreeDumperNode("receiverPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverPlaceholderOpt, Nothing)})
})
End Function
Public Overrides Function VisitConvertedTupleElements(node As BoundConvertedTupleElements, arg As Object) As TreeDumperNode
Return New TreeDumperNode("convertedTupleElements", Nothing, New TreeDumperNode() {
New TreeDumperNode("elementPlaceholders", Nothing, From x In node.ElementPlaceholders Select Visit(x, Nothing)),
New TreeDumperNode("convertedElements", Nothing, From x In node.ConvertedElements Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedConversion", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("inOutConversionFlags", node.InOutConversionFlags, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitDirectCast(node As BoundDirectCast, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[directCast]", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("conversionKind", node.ConversionKind, Nothing),
New TreeDumperNode("suppressVirtualCalls", node.SuppressVirtualCalls, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("relaxationLambdaOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationLambdaOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTryCast(node As BoundTryCast, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[tryCast]", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("conversionKind", node.ConversionKind, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("relaxationLambdaOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationLambdaOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeOf(node As BoundTypeOf, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[typeOf]", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("isTypeOfIsNotExpression", node.IsTypeOfIsNotExpression, Nothing),
New TreeDumperNode("targetType", node.TargetType, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSequencePoint(node As BoundSequencePoint, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequencePoint", Nothing, New TreeDumperNode() {
New TreeDumperNode("statementOpt", Nothing, new TreeDumperNode() {Visit(node.StatementOpt, Nothing)})
})
End Function
Public Overrides Function VisitSequencePointExpression(node As BoundSequencePointExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequencePointExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequencePointWithSpan", Nothing, New TreeDumperNode() {
New TreeDumperNode("statementOpt", Nothing, new TreeDumperNode() {Visit(node.StatementOpt, Nothing)}),
New TreeDumperNode("span", node.Span, Nothing)
})
End Function
Public Overrides Function VisitNoOpStatement(node As BoundNoOpStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("noOpStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("flavor", node.Flavor, Nothing)
})
End Function
Public Overrides Function VisitMethodGroup(node As BoundMethodGroup, arg As Object) As TreeDumperNode
Return New TreeDumperNode("methodGroup", Nothing, New TreeDumperNode() {
New TreeDumperNode("typeArgumentsOpt", Nothing, new TreeDumperNode() {Visit(node.TypeArgumentsOpt, Nothing)}),
New TreeDumperNode("methods", node.Methods, Nothing),
New TreeDumperNode("pendingExtensionMethodsOpt", node.PendingExtensionMethodsOpt, Nothing),
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("qualificationKind", node.QualificationKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPropertyGroup(node As BoundPropertyGroup, arg As Object) As TreeDumperNode
Return New TreeDumperNode("propertyGroup", Nothing, New TreeDumperNode() {
New TreeDumperNode("properties", node.Properties, Nothing),
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("qualificationKind", node.QualificationKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("returnStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expressionOpt", Nothing, new TreeDumperNode() {Visit(node.ExpressionOpt, Nothing)}),
New TreeDumperNode("functionLocalOpt", node.FunctionLocalOpt, Nothing),
New TreeDumperNode("exitLabelOpt", node.ExitLabelOpt, Nothing)
})
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("yieldStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)})
})
End Function
Public Overrides Function VisitThrowStatement(node As BoundThrowStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("throwStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expressionOpt", Nothing, new TreeDumperNode() {Visit(node.ExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitRedimStatement(node As BoundRedimStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("redimStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("clauses", Nothing, From x In node.Clauses Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitRedimClause(node As BoundRedimClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("redimClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("indices", Nothing, From x In node.Indices Select Visit(x, Nothing)),
New TreeDumperNode("arrayTypeOpt", node.ArrayTypeOpt, Nothing),
New TreeDumperNode("preserve", node.Preserve, Nothing)
})
End Function
Public Overrides Function VisitEraseStatement(node As BoundEraseStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("eraseStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("clauses", Nothing, From x In node.Clauses Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitCall(node As BoundCall, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[call]", Nothing, New TreeDumperNode() {
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("methodGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodGroupOpt, Nothing)}),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("defaultArguments", node.DefaultArguments, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("suppressObjectClone", node.SuppressObjectClone, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAttribute(node As BoundAttribute, arg As Object) As TreeDumperNode
Return New TreeDumperNode("attribute", Nothing, New TreeDumperNode() {
New TreeDumperNode("constructor", node.Constructor, Nothing),
New TreeDumperNode("constructorArguments", Nothing, From x In node.ConstructorArguments Select Visit(x, Nothing)),
New TreeDumperNode("namedArguments", Nothing, From x In node.NamedArguments Select Visit(x, Nothing)),
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateMemberAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("nameOpt", node.NameOpt, Nothing),
New TreeDumperNode("containerTypeOpt", node.ContainerTypeOpt, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("typeArgumentsOpt", Nothing, new TreeDumperNode() {Visit(node.TypeArgumentsOpt, Nothing)}),
New TreeDumperNode("accessKind", node.AccessKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateInvocation(node As BoundLateInvocation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateInvocation", Nothing, New TreeDumperNode() {
New TreeDumperNode("member", Nothing, new TreeDumperNode() {Visit(node.Member, Nothing)}),
New TreeDumperNode("argumentsOpt", Nothing, From x In node.ArgumentsOpt Select Visit(x, Nothing)),
New TreeDumperNode("argumentNamesOpt", node.ArgumentNamesOpt, Nothing),
New TreeDumperNode("accessKind", node.AccessKind, Nothing),
New TreeDumperNode("methodOrPropertyGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodOrPropertyGroupOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateAddressOfOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("memberAccess", Nothing, new TreeDumperNode() {Visit(node.MemberAccess, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("tupleLiteral", Nothing, New TreeDumperNode() {
New TreeDumperNode("inferredType", node.InferredType, Nothing),
New TreeDumperNode("argumentNamesOpt", node.ArgumentNamesOpt, Nothing),
New TreeDumperNode("inferredNamesOpt", node.InferredNamesOpt, Nothing),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("convertedTupleLiteral", Nothing, New TreeDumperNode() {
New TreeDumperNode("naturalTypeOpt", node.NaturalTypeOpt, Nothing),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("objectCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("constructorOpt", node.ConstructorOpt, Nothing),
New TreeDumperNode("methodGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodGroupOpt, Nothing)}),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("defaultArguments", node.DefaultArguments, Nothing),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("noPiaObjectCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("guidString", node.GuidString, Nothing),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("anonymousTypeCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("binderOpt", node.BinderOpt, Nothing),
New TreeDumperNode("declarations", Nothing, From x In node.Declarations Select Visit(x, Nothing)),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("anonymousTypePropertyAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("propertyIndex", node.PropertyIndex, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("anonymousTypeFieldInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("objectInitializerExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("createTemporaryLocalForInitialization", node.CreateTemporaryLocalForInitialization, Nothing),
New TreeDumperNode("placeholderOpt", Nothing, new TreeDumperNode() {Visit(node.PlaceholderOpt, Nothing)}),
New TreeDumperNode("initializers", Nothing, From x In node.Initializers Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("collectionInitializerExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("placeholderOpt", Nothing, new TreeDumperNode() {Visit(node.PlaceholderOpt, Nothing)}),
New TreeDumperNode("initializers", Nothing, From x In node.Initializers Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNewT(node As BoundNewT, arg As Object) As TreeDumperNode
Return New TreeDumperNode("newT", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("delegateCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("relaxationLambdaOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationLambdaOpt, Nothing)}),
New TreeDumperNode("relaxationReceiverPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationReceiverPlaceholderOpt, Nothing)}),
New TreeDumperNode("methodGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodGroupOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayCreation(node As BoundArrayCreation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayCreation", Nothing, New TreeDumperNode() {
New TreeDumperNode("isParamArrayArgument", node.IsParamArrayArgument, Nothing),
New TreeDumperNode("bounds", Nothing, From x In node.Bounds Select Visit(x, Nothing)),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("arrayLiteralOpt", Nothing, new TreeDumperNode() {Visit(node.ArrayLiteralOpt, Nothing)}),
New TreeDumperNode("arrayLiteralConversion", node.ArrayLiteralConversion, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayLiteral(node As BoundArrayLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayLiteral", Nothing, New TreeDumperNode() {
New TreeDumperNode("hasDominantType", node.HasDominantType, Nothing),
New TreeDumperNode("numberOfCandidates", node.NumberOfCandidates, Nothing),
New TreeDumperNode("inferredType", node.InferredType, Nothing),
New TreeDumperNode("bounds", Nothing, From x In node.Bounds Select Visit(x, Nothing)),
New TreeDumperNode("initializer", Nothing, new TreeDumperNode() {Visit(node.Initializer, Nothing)}),
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayInitialization", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializers", Nothing, From x In node.Initializers Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("fieldAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("fieldSymbol", node.FieldSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("suppressVirtualCalls", node.SuppressVirtualCalls, Nothing),
New TreeDumperNode("constantsInProgressOpt", node.ConstantsInProgressOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("propertyAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("propertySymbol", node.PropertySymbol, Nothing),
New TreeDumperNode("propertyGroupOpt", Nothing, new TreeDumperNode() {Visit(node.PropertyGroupOpt, Nothing)}),
New TreeDumperNode("accessKind", node.AccessKind, Nothing),
New TreeDumperNode("isWriteable", node.IsWriteable, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("defaultArguments", node.DefaultArguments, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitEventAccess(node As BoundEventAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("eventAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("eventSymbol", node.EventSymbol, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBlock(node As BoundBlock, arg As Object) As TreeDumperNode
Return New TreeDumperNode("block", Nothing, New TreeDumperNode() {
New TreeDumperNode("statementListSyntax", node.StatementListSyntax, Nothing),
New TreeDumperNode("locals", node.Locals, Nothing),
New TreeDumperNode("statements", Nothing, From x In node.Statements Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitStateMachineScope(node As BoundStateMachineScope, arg As Object) As TreeDumperNode
Return New TreeDumperNode("stateMachineScope", Nothing, New TreeDumperNode() {
New TreeDumperNode("fields", node.Fields, Nothing),
New TreeDumperNode("statement", Nothing, new TreeDumperNode() {Visit(node.Statement, Nothing)})
})
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration, arg As Object) As TreeDumperNode
Return New TreeDumperNode("localDeclaration", Nothing, New TreeDumperNode() {
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("declarationInitializerOpt", Nothing, new TreeDumperNode() {Visit(node.DeclarationInitializerOpt, Nothing)}),
New TreeDumperNode("identifierInitializerOpt", Nothing, new TreeDumperNode() {Visit(node.IdentifierInitializerOpt, Nothing)}),
New TreeDumperNode("initializedByAsNew", node.InitializedByAsNew, Nothing)
})
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations, arg As Object) As TreeDumperNode
Return New TreeDumperNode("asNewLocalDeclarations", Nothing, New TreeDumperNode() {
New TreeDumperNode("localDeclarations", Nothing, From x In node.LocalDeclarations Select Visit(x, Nothing)),
New TreeDumperNode("initializer", Nothing, new TreeDumperNode() {Visit(node.Initializer, Nothing)}),
New TreeDumperNode("binder", node.Binder, Nothing)
})
End Function
Public Overrides Function VisitDimStatement(node As BoundDimStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("dimStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("localDeclarations", Nothing, From x In node.LocalDeclarations Select Visit(x, Nothing)),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)})
})
End Function
Public Overrides Function VisitInitializer(node As BoundInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("initializer", Nothing, Array.Empty(Of TreeDumperNode)())
End Function
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("fieldInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializedFields", node.InitializedFields, Nothing),
New TreeDumperNode("memberAccessExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.MemberAccessExpressionOpt, Nothing)}),
New TreeDumperNode("initialValue", Nothing, new TreeDumperNode() {Visit(node.InitialValue, Nothing)}),
New TreeDumperNode("binderOpt", node.BinderOpt, Nothing)
})
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("propertyInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializedProperties", node.InitializedProperties, Nothing),
New TreeDumperNode("memberAccessExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.MemberAccessExpressionOpt, Nothing)}),
New TreeDumperNode("initialValue", Nothing, new TreeDumperNode() {Visit(node.InitialValue, Nothing)}),
New TreeDumperNode("binderOpt", node.BinderOpt, Nothing)
})
End Function
Public Overrides Function VisitParameterEqualsValue(node As BoundParameterEqualsValue, arg As Object) As TreeDumperNode
Return New TreeDumperNode("parameterEqualsValue", Nothing, New TreeDumperNode() {
New TreeDumperNode("parameter", node.Parameter, Nothing),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)})
})
End Function
Public Overrides Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("globalStatementInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("statement", Nothing, new TreeDumperNode() {Visit(node.Statement, Nothing)})
})
End Function
Public Overrides Function VisitSequence(node As BoundSequence, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequence", Nothing, New TreeDumperNode() {
New TreeDumperNode("locals", node.Locals, Nothing),
New TreeDumperNode("sideEffects", Nothing, From x In node.SideEffects Select Visit(x, Nothing)),
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("expressionStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)})
})
End Function
Public Overrides Function VisitIfStatement(node As BoundIfStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("ifStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("consequence", Nothing, new TreeDumperNode() {Visit(node.Consequence, Nothing)}),
New TreeDumperNode("alternativeOpt", Nothing, new TreeDumperNode() {Visit(node.AlternativeOpt, Nothing)})
})
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("selectStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expressionStatement", Nothing, new TreeDumperNode() {Visit(node.ExpressionStatement, Nothing)}),
New TreeDumperNode("exprPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.ExprPlaceholderOpt, Nothing)}),
New TreeDumperNode("caseBlocks", Nothing, From x In node.CaseBlocks Select Visit(x, Nothing)),
New TreeDumperNode("recommendSwitchTable", node.RecommendSwitchTable, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock, arg As Object) As TreeDumperNode
Return New TreeDumperNode("caseBlock", Nothing, New TreeDumperNode() {
New TreeDumperNode("caseStatement", Nothing, new TreeDumperNode() {Visit(node.CaseStatement, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)})
})
End Function
Public Overrides Function VisitCaseStatement(node As BoundCaseStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("caseStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("caseClauses", Nothing, From x In node.CaseClauses Select Visit(x, Nothing)),
New TreeDumperNode("conditionOpt", Nothing, new TreeDumperNode() {Visit(node.ConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitSimpleCaseClause(node As BoundSimpleCaseClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("simpleCaseClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("conditionOpt", Nothing, new TreeDumperNode() {Visit(node.ConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitRangeCaseClause(node As BoundRangeCaseClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rangeCaseClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("lowerBoundOpt", Nothing, new TreeDumperNode() {Visit(node.LowerBoundOpt, Nothing)}),
New TreeDumperNode("upperBoundOpt", Nothing, new TreeDumperNode() {Visit(node.UpperBoundOpt, Nothing)}),
New TreeDumperNode("lowerBoundConditionOpt", Nothing, new TreeDumperNode() {Visit(node.LowerBoundConditionOpt, Nothing)}),
New TreeDumperNode("upperBoundConditionOpt", Nothing, new TreeDumperNode() {Visit(node.UpperBoundConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitRelationalCaseClause(node As BoundRelationalCaseClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("relationalCaseClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("conditionOpt", Nothing, new TreeDumperNode() {Visit(node.ConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitDoLoopStatement(node As BoundDoLoopStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("doLoopStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("topConditionOpt", Nothing, new TreeDumperNode() {Visit(node.TopConditionOpt, Nothing)}),
New TreeDumperNode("bottomConditionOpt", Nothing, new TreeDumperNode() {Visit(node.BottomConditionOpt, Nothing)}),
New TreeDumperNode("topConditionIsUntil", node.TopConditionIsUntil, Nothing),
New TreeDumperNode("bottomConditionIsUntil", node.BottomConditionIsUntil, Nothing),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("whileStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators, arg As Object) As TreeDumperNode
Return New TreeDumperNode("forToUserDefinedOperators", Nothing, New TreeDumperNode() {
New TreeDumperNode("leftOperandPlaceholder", Nothing, new TreeDumperNode() {Visit(node.LeftOperandPlaceholder, Nothing)}),
New TreeDumperNode("rightOperandPlaceholder", Nothing, new TreeDumperNode() {Visit(node.RightOperandPlaceholder, Nothing)}),
New TreeDumperNode("addition", Nothing, new TreeDumperNode() {Visit(node.Addition, Nothing)}),
New TreeDumperNode("subtraction", Nothing, new TreeDumperNode() {Visit(node.Subtraction, Nothing)}),
New TreeDumperNode("lessThanOrEqual", Nothing, new TreeDumperNode() {Visit(node.LessThanOrEqual, Nothing)}),
New TreeDumperNode("greaterThanOrEqual", Nothing, new TreeDumperNode() {Visit(node.GreaterThanOrEqual, Nothing)})
})
End Function
Public Overrides Function VisitForToStatement(node As BoundForToStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("forToStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("initialValue", Nothing, new TreeDumperNode() {Visit(node.InitialValue, Nothing)}),
New TreeDumperNode("limitValue", Nothing, new TreeDumperNode() {Visit(node.LimitValue, Nothing)}),
New TreeDumperNode("stepValue", Nothing, new TreeDumperNode() {Visit(node.StepValue, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("operatorsOpt", Nothing, new TreeDumperNode() {Visit(node.OperatorsOpt, Nothing)}),
New TreeDumperNode("declaredOrInferredLocalOpt", node.DeclaredOrInferredLocalOpt, Nothing),
New TreeDumperNode("controlVariable", Nothing, new TreeDumperNode() {Visit(node.ControlVariable, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("nextVariablesOpt", Nothing, From x In node.NextVariablesOpt Select Visit(x, Nothing)),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitForEachStatement(node As BoundForEachStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("forEachStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("collection", Nothing, new TreeDumperNode() {Visit(node.Collection, Nothing)}),
New TreeDumperNode("enumeratorInfo", node.EnumeratorInfo, Nothing),
New TreeDumperNode("declaredOrInferredLocalOpt", node.DeclaredOrInferredLocalOpt, Nothing),
New TreeDumperNode("controlVariable", Nothing, new TreeDumperNode() {Visit(node.ControlVariable, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("nextVariablesOpt", Nothing, From x In node.NextVariablesOpt Select Visit(x, Nothing)),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitExitStatement(node As BoundExitStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("exitStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitContinueStatement(node As BoundContinueStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("continueStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("tryStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("tryBlock", Nothing, new TreeDumperNode() {Visit(node.TryBlock, Nothing)}),
New TreeDumperNode("catchBlocks", Nothing, From x In node.CatchBlocks Select Visit(x, Nothing)),
New TreeDumperNode("finallyBlockOpt", Nothing, new TreeDumperNode() {Visit(node.FinallyBlockOpt, Nothing)}),
New TreeDumperNode("exitLabelOpt", node.ExitLabelOpt, Nothing)
})
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock, arg As Object) As TreeDumperNode
Return New TreeDumperNode("catchBlock", Nothing, New TreeDumperNode() {
New TreeDumperNode("localOpt", node.LocalOpt, Nothing),
New TreeDumperNode("exceptionSourceOpt", Nothing, new TreeDumperNode() {Visit(node.ExceptionSourceOpt, Nothing)}),
New TreeDumperNode("errorLineNumberOpt", Nothing, new TreeDumperNode() {Visit(node.ErrorLineNumberOpt, Nothing)}),
New TreeDumperNode("exceptionFilterOpt", Nothing, new TreeDumperNode() {Visit(node.ExceptionFilterOpt, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("isSynthesizedAsyncCatchAll", node.IsSynthesizedAsyncCatchAll, Nothing)
})
End Function
Public Overrides Function VisitLiteral(node As BoundLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("literal", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", node.Value, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("meReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("valueTypeMeReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("myBaseReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("myClassReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("previousSubmissionReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("sourceType", node.SourceType, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("hostObjectMemberReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLocal(node As BoundLocal, arg As Object) As TreeDumperNode
Return New TreeDumperNode("local", Nothing, New TreeDumperNode() {
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPseudoVariable(node As BoundPseudoVariable, arg As Object) As TreeDumperNode
Return New TreeDumperNode("pseudoVariable", Nothing, New TreeDumperNode() {
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("emitExpressions", node.EmitExpressions, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitParameter(node As BoundParameter, arg As Object) As TreeDumperNode
Return New TreeDumperNode("parameter", Nothing, New TreeDumperNode() {
New TreeDumperNode("parameterSymbol", node.ParameterSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("suppressVirtualCalls", node.SuppressVirtualCalls, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("byRefArgumentPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("isOut", node.IsOut, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack, arg As Object) As TreeDumperNode
Return New TreeDumperNode("byRefArgumentWithCopyBack", Nothing, New TreeDumperNode() {
New TreeDumperNode("originalArgument", Nothing, new TreeDumperNode() {Visit(node.OriginalArgument, Nothing)}),
New TreeDumperNode("inConversion", Nothing, new TreeDumperNode() {Visit(node.InConversion, Nothing)}),
New TreeDumperNode("inPlaceholder", Nothing, new TreeDumperNode() {Visit(node.InPlaceholder, Nothing)}),
New TreeDumperNode("outConversion", Nothing, new TreeDumperNode() {Visit(node.OutConversion, Nothing)}),
New TreeDumperNode("outPlaceholder", Nothing, new TreeDumperNode() {Visit(node.OutPlaceholder, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateBoundArgumentSupportingAssignmentWithCapture", Nothing, New TreeDumperNode() {
New TreeDumperNode("originalArgument", Nothing, new TreeDumperNode() {Visit(node.OriginalArgument, Nothing)}),
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("labelStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitLabel(node As BoundLabel, arg As Object) As TreeDumperNode
Return New TreeDumperNode("label", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("gotoStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing),
New TreeDumperNode("labelExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.LabelExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitStatementList(node As BoundStatementList, arg As Object) As TreeDumperNode
Return New TreeDumperNode("statementList", Nothing, New TreeDumperNode() {
New TreeDumperNode("statements", Nothing, From x In node.Statements Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conditionalGoto", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("jumpIfTrue", node.JumpIfTrue, Nothing),
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("withStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("originalExpression", Nothing, new TreeDumperNode() {Visit(node.OriginalExpression, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("binder", node.Binder, Nothing)
})
End Function
Public Overrides Function VisitUnboundLambda(node As UnboundLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unboundLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("flags", node.Flags, Nothing),
New TreeDumperNode("parameters", node.Parameters, Nothing),
New TreeDumperNode("returnType", node.ReturnType, Nothing),
New TreeDumperNode("bindingCache", node.BindingCache, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLambda(node As BoundLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("lambdaSymbol", node.LambdaSymbol, Nothing),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("diagnostics", node.Diagnostics, Nothing),
New TreeDumperNode("lambdaBinderOpt", node.LambdaBinderOpt, Nothing),
New TreeDumperNode("delegateRelaxation", node.DelegateRelaxation, Nothing),
New TreeDumperNode("methodConversionKind", node.MethodConversionKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("lastOperator", Nothing, new TreeDumperNode() {Visit(node.LastOperator, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource, arg As Object) As TreeDumperNode
Return New TreeDumperNode("querySource", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion, arg As Object) As TreeDumperNode
Return New TreeDumperNode("toQueryableCollectionConversion", Nothing, New TreeDumperNode() {
New TreeDumperNode("conversionCall", Nothing, new TreeDumperNode() {Visit(node.ConversionCall, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryableSource", Nothing, New TreeDumperNode() {
New TreeDumperNode("source", Nothing, new TreeDumperNode() {Visit(node.Source, Nothing)}),
New TreeDumperNode("rangeVariableOpt", node.RangeVariableOpt, Nothing),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("compoundVariableType", node.CompoundVariableType, Nothing),
New TreeDumperNode("binders", node.Binders, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("compoundVariableType", node.CompoundVariableType, Nothing),
New TreeDumperNode("binders", node.Binders, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering, arg As Object) As TreeDumperNode
Return New TreeDumperNode("ordering", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("lambdaSymbol", node.LambdaSymbol, Nothing),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("exprIsOperandOfConditionalBranch", node.ExprIsOperandOfConditionalBranch, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rangeVariableAssignment", Nothing, New TreeDumperNode() {
New TreeDumperNode("rangeVariable", node.RangeVariable, Nothing),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("groupTypeInferenceLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("parameters", node.Parameters, Nothing),
New TreeDumperNode("compilation", node.Compilation, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("aggregateClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("capturedGroupOpt", Nothing, new TreeDumperNode() {Visit(node.CapturedGroupOpt, Nothing)}),
New TreeDumperNode("groupPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.GroupPlaceholderOpt, Nothing)}),
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("compoundVariableType", node.CompoundVariableType, Nothing),
New TreeDumperNode("binders", node.Binders, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGroupAggregation(node As BoundGroupAggregation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("groupAggregation", Nothing, New TreeDumperNode() {
New TreeDumperNode("group", Nothing, new TreeDumperNode() {Visit(node.Group, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rangeVariable", Nothing, New TreeDumperNode() {
New TreeDumperNode("rangeVariable", node.RangeVariable, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAddHandlerStatement(node As BoundAddHandlerStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("addHandlerStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("eventAccess", Nothing, new TreeDumperNode() {Visit(node.EventAccess, Nothing)}),
New TreeDumperNode("handler", Nothing, new TreeDumperNode() {Visit(node.Handler, Nothing)})
})
End Function
Public Overrides Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("removeHandlerStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("eventAccess", Nothing, new TreeDumperNode() {Visit(node.EventAccess, Nothing)}),
New TreeDumperNode("handler", Nothing, new TreeDumperNode() {Visit(node.Handler, Nothing)})
})
End Function
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("raiseEventStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("eventSymbol", node.EventSymbol, Nothing),
New TreeDumperNode("eventInvocation", Nothing, new TreeDumperNode() {Visit(node.EventInvocation, Nothing)})
})
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("usingStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("resourceList", Nothing, From x In node.ResourceList Select Visit(x, Nothing)),
New TreeDumperNode("resourceExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.ResourceExpressionOpt, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("usingInfo", node.UsingInfo, Nothing),
New TreeDumperNode("locals", node.Locals, Nothing)
})
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("syncLockStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("lockExpression", Nothing, new TreeDumperNode() {Visit(node.LockExpression, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)})
})
End Function
Public Overrides Function VisitXmlName(node As BoundXmlName, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlName", Nothing, New TreeDumperNode() {
New TreeDumperNode("xmlNamespace", Nothing, new TreeDumperNode() {Visit(node.XmlNamespace, Nothing)}),
New TreeDumperNode("localName", Nothing, new TreeDumperNode() {Visit(node.LocalName, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlNamespace(node As BoundXmlNamespace, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlNamespace", Nothing, New TreeDumperNode() {
New TreeDumperNode("xmlNamespace", Nothing, new TreeDumperNode() {Visit(node.XmlNamespace, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlDocument(node As BoundXmlDocument, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlDocument", Nothing, New TreeDumperNode() {
New TreeDumperNode("declaration", Nothing, new TreeDumperNode() {Visit(node.Declaration, Nothing)}),
New TreeDumperNode("childNodes", Nothing, From x In node.ChildNodes Select Visit(x, Nothing)),
New TreeDumperNode("rewriterInfo", node.RewriterInfo, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlDeclaration", Nothing, New TreeDumperNode() {
New TreeDumperNode("version", Nothing, new TreeDumperNode() {Visit(node.Version, Nothing)}),
New TreeDumperNode("encoding", Nothing, new TreeDumperNode() {Visit(node.Encoding, Nothing)}),
New TreeDumperNode("standalone", Nothing, new TreeDumperNode() {Visit(node.Standalone, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlProcessingInstruction", Nothing, New TreeDumperNode() {
New TreeDumperNode("target", Nothing, new TreeDumperNode() {Visit(node.Target, Nothing)}),
New TreeDumperNode("data", Nothing, new TreeDumperNode() {Visit(node.Data, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlComment(node As BoundXmlComment, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlComment", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlAttribute(node As BoundXmlAttribute, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlAttribute", Nothing, New TreeDumperNode() {
New TreeDumperNode("name", Nothing, new TreeDumperNode() {Visit(node.Name, Nothing)}),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("matchesImport", node.MatchesImport, Nothing),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlElement(node As BoundXmlElement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlElement", Nothing, New TreeDumperNode() {
New TreeDumperNode("argument", Nothing, new TreeDumperNode() {Visit(node.Argument, Nothing)}),
New TreeDumperNode("childNodes", Nothing, From x In node.ChildNodes Select Visit(x, Nothing)),
New TreeDumperNode("rewriterInfo", node.RewriterInfo, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlMemberAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("memberAccess", Nothing, new TreeDumperNode() {Visit(node.MemberAccess, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlEmbeddedExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlCData(node As BoundXmlCData, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlCData", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("resumeStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("resumeKind", node.ResumeKind, Nothing),
New TreeDumperNode("labelOpt", node.LabelOpt, Nothing),
New TreeDumperNode("labelExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.LabelExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("onErrorStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("onErrorKind", node.OnErrorKind, Nothing),
New TreeDumperNode("labelOpt", node.LabelOpt, Nothing),
New TreeDumperNode("labelExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.LabelExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionHandlingStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("containsOnError", node.ContainsOnError, Nothing),
New TreeDumperNode("containsResume", node.ContainsResume, Nothing),
New TreeDumperNode("resumeWithoutLabelOpt", node.ResumeWithoutLabelOpt, Nothing),
New TreeDumperNode("trackLineNumber", node.TrackLineNumber, Nothing),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)})
})
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionHandlingCatchFilter", Nothing, New TreeDumperNode() {
New TreeDumperNode("activeHandlerLocal", Nothing, new TreeDumperNode() {Visit(node.ActiveHandlerLocal, Nothing)}),
New TreeDumperNode("resumeTargetLocal", Nothing, new TreeDumperNode() {Visit(node.ResumeTargetLocal, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionOnErrorSwitch", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("jumps", Nothing, From x In node.Jumps Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionResumeSwitch", Nothing, New TreeDumperNode() {
New TreeDumperNode("resumeTargetTemporary", Nothing, new TreeDumperNode() {Visit(node.ResumeTargetTemporary, Nothing)}),
New TreeDumperNode("resumeLabel", Nothing, new TreeDumperNode() {Visit(node.ResumeLabel, Nothing)}),
New TreeDumperNode("resumeNextLabel", Nothing, new TreeDumperNode() {Visit(node.ResumeNextLabel, Nothing)}),
New TreeDumperNode("jumps", Nothing, From x In node.Jumps Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("awaitOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("awaitableInstancePlaceholder", Nothing, new TreeDumperNode() {Visit(node.AwaitableInstancePlaceholder, Nothing)}),
New TreeDumperNode("getAwaiter", Nothing, new TreeDumperNode() {Visit(node.GetAwaiter, Nothing)}),
New TreeDumperNode("awaiterInstancePlaceholder", Nothing, new TreeDumperNode() {Visit(node.AwaiterInstancePlaceholder, Nothing)}),
New TreeDumperNode("isCompleted", Nothing, new TreeDumperNode() {Visit(node.IsCompleted, Nothing)}),
New TreeDumperNode("getResult", Nothing, new TreeDumperNode() {Visit(node.GetResult, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSpillSequence(node As BoundSpillSequence, arg As Object) As TreeDumperNode
Return New TreeDumperNode("spillSequence", Nothing, New TreeDumperNode() {
New TreeDumperNode("locals", node.Locals, Nothing),
New TreeDumperNode("spillFields", node.SpillFields, Nothing),
New TreeDumperNode("statements", Nothing, From x In node.Statements Select Visit(x, Nothing)),
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitStopStatement(node As BoundStopStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("stopStatement", Nothing, Array.Empty(Of TreeDumperNode)())
End Function
Public Overrides Function VisitEndStatement(node As BoundEndStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("endStatement", Nothing, Array.Empty(Of TreeDumperNode)())
End Function
Public Overrides Function VisitMidResult(node As BoundMidResult, arg As Object) As TreeDumperNode
Return New TreeDumperNode("midResult", Nothing, New TreeDumperNode() {
New TreeDumperNode("original", Nothing, new TreeDumperNode() {Visit(node.Original, Nothing)}),
New TreeDumperNode("start", Nothing, new TreeDumperNode() {Visit(node.Start, Nothing)}),
New TreeDumperNode("lengthOpt", Nothing, new TreeDumperNode() {Visit(node.LengthOpt, Nothing)}),
New TreeDumperNode("source", Nothing, new TreeDumperNode() {Visit(node.Source, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conditionalAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiver", Nothing, new TreeDumperNode() {Visit(node.Receiver, Nothing)}),
New TreeDumperNode("placeholder", Nothing, new TreeDumperNode() {Visit(node.Placeholder, Nothing)}),
New TreeDumperNode("accessExpression", Nothing, new TreeDumperNode() {Visit(node.AccessExpression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conditionalAccessReceiverPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("placeholderId", node.PlaceholderId, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("loweredConditionalAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOrCondition", Nothing, new TreeDumperNode() {Visit(node.ReceiverOrCondition, Nothing)}),
New TreeDumperNode("captureReceiver", node.CaptureReceiver, Nothing),
New TreeDumperNode("placeholderId", node.PlaceholderId, Nothing),
New TreeDumperNode("whenNotNull", Nothing, new TreeDumperNode() {Visit(node.WhenNotNull, Nothing)}),
New TreeDumperNode("whenNullOpt", Nothing, new TreeDumperNode() {Visit(node.WhenNullOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver, arg As Object) As TreeDumperNode
Return New TreeDumperNode("complexConditionalAccessReceiver", Nothing, New TreeDumperNode() {
New TreeDumperNode("valueTypeReceiver", Nothing, new TreeDumperNode() {Visit(node.ValueTypeReceiver, Nothing)}),
New TreeDumperNode("referenceTypeReceiver", Nothing, new TreeDumperNode() {Visit(node.ReferenceTypeReceiver, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNameOfOperator(node As BoundNameOfOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("nameOfOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("argument", Nothing, new TreeDumperNode() {Visit(node.Argument, Nothing)}),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeAsValueExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("interpolatedStringExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("contents", Nothing, From x In node.Contents Select Visit(x, Nothing)),
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitInterpolation(node As BoundInterpolation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("interpolation", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("alignmentOpt", Nothing, new TreeDumperNode() {Visit(node.AlignmentOpt, Nothing)}),
New TreeDumperNode("formatStringOpt", Nothing, new TreeDumperNode() {Visit(node.FormatStringOpt, Nothing)})
})
End Function
End Class
End Namespace
| ' <auto-generated />
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Runtime.CompilerServices
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Enum BoundKind as Byte
TypeArguments
OmittedArgument
LValueToRValueWrapper
WithLValueExpressionPlaceholder
WithRValueExpressionPlaceholder
RValuePlaceholder
LValuePlaceholder
Dup
BadExpression
BadStatement
Parenthesized
BadVariable
ArrayAccess
ArrayLength
[GetType]
FieldInfo
MethodInfo
TypeExpression
TypeOrValueExpression
NamespaceExpression
MethodDefIndex
MaximumMethodDefIndex
InstrumentationPayloadRoot
ModuleVersionId
ModuleVersionIdString
SourceDocumentIndex
UnaryOperator
UserDefinedUnaryOperator
NullableIsTrueOperator
BinaryOperator
UserDefinedBinaryOperator
UserDefinedShortCircuitingOperator
CompoundAssignmentTargetPlaceholder
AssignmentOperator
ReferenceAssignment
AddressOfOperator
TernaryConditionalExpression
BinaryConditionalExpression
Conversion
RelaxationLambda
ConvertedTupleElements
UserDefinedConversion
[DirectCast]
[TryCast]
[TypeOf]
SequencePoint
SequencePointExpression
SequencePointWithSpan
NoOpStatement
MethodGroup
PropertyGroup
ReturnStatement
YieldStatement
ThrowStatement
RedimStatement
RedimClause
EraseStatement
[Call]
Attribute
LateMemberAccess
LateInvocation
LateAddressOfOperator
TupleLiteral
ConvertedTupleLiteral
ObjectCreationExpression
NoPiaObjectCreationExpression
AnonymousTypeCreationExpression
AnonymousTypePropertyAccess
AnonymousTypeFieldInitializer
ObjectInitializerExpression
CollectionInitializerExpression
NewT
DelegateCreationExpression
ArrayCreation
ArrayLiteral
ArrayInitialization
FieldAccess
PropertyAccess
EventAccess
Block
StateMachineScope
LocalDeclaration
AsNewLocalDeclarations
DimStatement
Initializer
FieldInitializer
PropertyInitializer
ParameterEqualsValue
GlobalStatementInitializer
Sequence
ExpressionStatement
IfStatement
SelectStatement
CaseBlock
CaseStatement
SimpleCaseClause
RangeCaseClause
RelationalCaseClause
DoLoopStatement
WhileStatement
ForToUserDefinedOperators
ForToStatement
ForEachStatement
ExitStatement
ContinueStatement
TryStatement
CatchBlock
Literal
MeReference
ValueTypeMeReference
MyBaseReference
MyClassReference
PreviousSubmissionReference
HostObjectMemberReference
Local
PseudoVariable
Parameter
ByRefArgumentPlaceholder
ByRefArgumentWithCopyBack
LateBoundArgumentSupportingAssignmentWithCapture
LabelStatement
Label
GotoStatement
StatementList
ConditionalGoto
WithStatement
UnboundLambda
Lambda
QueryExpression
QuerySource
ToQueryableCollectionConversion
QueryableSource
QueryClause
Ordering
QueryLambda
RangeVariableAssignment
GroupTypeInferenceLambda
AggregateClause
GroupAggregation
RangeVariable
AddHandlerStatement
RemoveHandlerStatement
RaiseEventStatement
UsingStatement
SyncLockStatement
XmlName
XmlNamespace
XmlDocument
XmlDeclaration
XmlProcessingInstruction
XmlComment
XmlAttribute
XmlElement
XmlMemberAccess
XmlEmbeddedExpression
XmlCData
ResumeStatement
OnErrorStatement
UnstructuredExceptionHandlingStatement
UnstructuredExceptionHandlingCatchFilter
UnstructuredExceptionOnErrorSwitch
UnstructuredExceptionResumeSwitch
AwaitOperator
SpillSequence
StopStatement
EndStatement
MidResult
ConditionalAccess
ConditionalAccessReceiverPlaceholder
LoweredConditionalAccess
ComplexConditionalAccessReceiver
NameOfOperator
TypeAsValueExpression
InterpolatedStringExpression
Interpolation
End Enum
Partial Friend MustInherit Class BoundExpression
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
Me._Type = type
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax)
Me._Type = type
End Sub
Private ReadOnly _Type As TypeSymbol
Public ReadOnly Property Type As TypeSymbol
Get
Return _Type
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundTypeArguments
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, arguments As ImmutableArray(Of TypeSymbol), hasErrors As Boolean)
MyBase.New(BoundKind.TypeArguments, syntax, Nothing, hasErrors)
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Arguments = arguments
End Sub
Public Sub New(syntax As SyntaxNode, arguments As ImmutableArray(Of TypeSymbol))
MyBase.New(BoundKind.TypeArguments, syntax, Nothing)
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Arguments = arguments
End Sub
Private ReadOnly _Arguments As ImmutableArray(Of TypeSymbol)
Public ReadOnly Property Arguments As ImmutableArray(Of TypeSymbol)
Get
Return _Arguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeArguments(Me)
End Function
Public Function Update(arguments As ImmutableArray(Of TypeSymbol)) As BoundTypeArguments
If arguments <> Me.Arguments Then
Dim result = New BoundTypeArguments(Me.Syntax, arguments, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundOmittedArgument
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.OmittedArgument, syntax, type, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.OmittedArgument, syntax, type)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitOmittedArgument(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundOmittedArgument
If type IsNot Me.Type Then
Dim result = New BoundOmittedArgument(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundValuePlaceholderBase
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundLValueToRValueWrapper
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, underlyingLValue As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LValueToRValueWrapper, syntax, type, hasErrors OrElse underlyingLValue.NonNullAndHasErrors())
Debug.Assert(underlyingLValue IsNot Nothing, "Field 'underlyingLValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingLValue = underlyingLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _UnderlyingLValue As BoundExpression
Public ReadOnly Property UnderlyingLValue As BoundExpression
Get
Return _UnderlyingLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLValueToRValueWrapper(Me)
End Function
Public Function Update(underlyingLValue As BoundExpression, type As TypeSymbol) As BoundLValueToRValueWrapper
If underlyingLValue IsNot Me.UnderlyingLValue OrElse type IsNot Me.Type Then
Dim result = New BoundLValueToRValueWrapper(Me.Syntax, underlyingLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundLValuePlaceholderBase
Inherits BoundValuePlaceholderBase
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend MustInherit Class BoundRValuePlaceholderBase
Inherits BoundValuePlaceholderBase
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundWithLValueExpressionPlaceholder
Inherits BoundLValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.WithLValueExpressionPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.WithLValueExpressionPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWithLValueExpressionPlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundWithLValueExpressionPlaceholder
If type IsNot Me.Type Then
Dim result = New BoundWithLValueExpressionPlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundWithRValueExpressionPlaceholder
Inherits BoundRValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.WithRValueExpressionPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.WithRValueExpressionPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWithRValueExpressionPlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundWithRValueExpressionPlaceholder
If type IsNot Me.Type Then
Dim result = New BoundWithRValueExpressionPlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRValuePlaceholder
Inherits BoundRValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.RValuePlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.RValuePlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRValuePlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundRValuePlaceholder
If type IsNot Me.Type Then
Dim result = New BoundRValuePlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLValuePlaceholder
Inherits BoundLValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.LValuePlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.LValuePlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLValuePlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundLValuePlaceholder
If type IsNot Me.Type Then
Dim result = New BoundLValuePlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDup
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, isReference As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Dup, syntax, type, hasErrors)
Me._IsReference = isReference
End Sub
Public Sub New(syntax As SyntaxNode, isReference As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.Dup, syntax, type)
Me._IsReference = isReference
End Sub
Private ReadOnly _IsReference As Boolean
Public ReadOnly Property IsReference As Boolean
Get
Return _IsReference
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDup(Me)
End Function
Public Function Update(isReference As Boolean, type As TypeSymbol) As BoundDup
If isReference <> Me.IsReference OrElse type IsNot Me.Type Then
Dim result = New BoundDup(Me.Syntax, isReference, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBadExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, resultKind As LookupResultKind, symbols As ImmutableArray(Of Symbol), childBoundNodes As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BadExpression, syntax, type, hasErrors OrElse childBoundNodes.NonNullAndHasErrors())
Debug.Assert(Not (symbols.IsDefault), "Field 'symbols' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (childBoundNodes.IsDefault), "Field 'childBoundNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ResultKind = resultKind
Me._Symbols = symbols
Me._ChildBoundNodes = childBoundNodes
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
Private ReadOnly _Symbols As ImmutableArray(Of Symbol)
Public ReadOnly Property Symbols As ImmutableArray(Of Symbol)
Get
Return _Symbols
End Get
End Property
Private ReadOnly _ChildBoundNodes As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ChildBoundNodes As ImmutableArray(Of BoundExpression)
Get
Return _ChildBoundNodes
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBadExpression(Me)
End Function
Public Function Update(resultKind As LookupResultKind, symbols As ImmutableArray(Of Symbol), childBoundNodes As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundBadExpression
If resultKind <> Me.ResultKind OrElse symbols <> Me.Symbols OrElse childBoundNodes <> Me.ChildBoundNodes OrElse type IsNot Me.Type Then
Dim result = New BoundBadExpression(Me.Syntax, resultKind, symbols, childBoundNodes, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBadStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, childBoundNodes As ImmutableArray(Of BoundNode), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BadStatement, syntax, hasErrors OrElse childBoundNodes.NonNullAndHasErrors())
Debug.Assert(Not (childBoundNodes.IsDefault), "Field 'childBoundNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ChildBoundNodes = childBoundNodes
End Sub
Private ReadOnly _ChildBoundNodes As ImmutableArray(Of BoundNode)
Public ReadOnly Property ChildBoundNodes As ImmutableArray(Of BoundNode)
Get
Return _ChildBoundNodes
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBadStatement(Me)
End Function
Public Function Update(childBoundNodes As ImmutableArray(Of BoundNode)) As BoundBadStatement
If childBoundNodes <> Me.ChildBoundNodes Then
Dim result = New BoundBadStatement(Me.Syntax, childBoundNodes, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundParenthesized
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Parenthesized, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitParenthesized(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundParenthesized
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundParenthesized(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBadVariable
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, isLValue As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BadVariable, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Me._IsLValue = isLValue
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBadVariable(Me)
End Function
Public Function Update(expression As BoundExpression, isLValue As Boolean, type As TypeSymbol) As BoundBadVariable
If expression IsNot Me.Expression OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundBadVariable(Me.Syntax, expression, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, indices As ImmutableArray(Of BoundExpression), isLValue As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayAccess, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors() OrElse indices.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (indices.IsDefault), "Field 'indices' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Me._Indices = indices
Me._IsLValue = isLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _Indices As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Indices As ImmutableArray(Of BoundExpression)
Get
Return _Indices
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayAccess(Me)
End Function
Public Function Update(expression As BoundExpression, indices As ImmutableArray(Of BoundExpression), isLValue As Boolean, type As TypeSymbol) As BoundArrayAccess
If expression IsNot Me.Expression OrElse indices <> Me.Indices OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundArrayAccess(Me.Syntax, expression, indices, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayLength
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayLength, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayLength(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundArrayLength
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundArrayLength(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGetType
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, sourceType As BoundTypeExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GetType, syntax, type, hasErrors OrElse sourceType.NonNullAndHasErrors())
Debug.Assert(sourceType IsNot Nothing, "Field 'sourceType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._SourceType = sourceType
End Sub
Private ReadOnly _SourceType As BoundTypeExpression
Public ReadOnly Property SourceType As BoundTypeExpression
Get
Return _SourceType
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGetType(Me)
End Function
Public Function Update(sourceType As BoundTypeExpression, type As TypeSymbol) As BoundGetType
If sourceType IsNot Me.SourceType OrElse type IsNot Me.Type Then
Dim result = New BoundGetType(Me.Syntax, sourceType, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundFieldInfo
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, field As FieldSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.FieldInfo, syntax, type, hasErrors)
Debug.Assert(field IsNot Nothing, "Field 'field' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Field = field
End Sub
Public Sub New(syntax As SyntaxNode, field As FieldSymbol, type As TypeSymbol)
MyBase.New(BoundKind.FieldInfo, syntax, type)
Debug.Assert(field IsNot Nothing, "Field 'field' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Field = field
End Sub
Private ReadOnly _Field As FieldSymbol
Public ReadOnly Property Field As FieldSymbol
Get
Return _Field
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitFieldInfo(Me)
End Function
Public Function Update(field As FieldSymbol, type As TypeSymbol) As BoundFieldInfo
If field IsNot Me.Field OrElse type IsNot Me.Type Then
Dim result = New BoundFieldInfo(Me.Syntax, field, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMethodInfo
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MethodInfo, syntax, type, hasErrors)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol)
MyBase.New(BoundKind.MethodInfo, syntax, type)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMethodInfo(Me)
End Function
Public Function Update(method As MethodSymbol, type As TypeSymbol) As BoundMethodInfo
If method IsNot Me.Method OrElse type IsNot Me.Type Then
Dim result = New BoundMethodInfo(Me.Syntax, method, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TypeExpression, syntax, type, hasErrors OrElse unevaluatedReceiverOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnevaluatedReceiverOpt = unevaluatedReceiverOpt
Me._AliasOpt = aliasOpt
End Sub
Private ReadOnly _UnevaluatedReceiverOpt As BoundExpression
Public ReadOnly Property UnevaluatedReceiverOpt As BoundExpression
Get
Return _UnevaluatedReceiverOpt
End Get
End Property
Private ReadOnly _AliasOpt As AliasSymbol
Public ReadOnly Property AliasOpt As AliasSymbol
Get
Return _AliasOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeExpression(Me)
End Function
Public Function Update(unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, type As TypeSymbol) As BoundTypeExpression
If unevaluatedReceiverOpt IsNot Me.UnevaluatedReceiverOpt OrElse aliasOpt IsNot Me.AliasOpt OrElse type IsNot Me.Type Then
Dim result = New BoundTypeExpression(Me.Syntax, unevaluatedReceiverOpt, aliasOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeOrValueExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, data As BoundTypeOrValueData, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.TypeOrValueExpression, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Data = data
End Sub
Public Sub New(syntax As SyntaxNode, data As BoundTypeOrValueData, type As TypeSymbol)
MyBase.New(BoundKind.TypeOrValueExpression, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Data = data
End Sub
Private ReadOnly _Data As BoundTypeOrValueData
Public ReadOnly Property Data As BoundTypeOrValueData
Get
Return _Data
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeOrValueExpression(Me)
End Function
Public Function Update(data As BoundTypeOrValueData, type As TypeSymbol) As BoundTypeOrValueExpression
If data <> Me.Data OrElse type IsNot Me.Type Then
Dim result = New BoundTypeOrValueExpression(Me.Syntax, data, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNamespaceExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, namespaceSymbol As NamespaceSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NamespaceExpression, syntax, Nothing, hasErrors OrElse unevaluatedReceiverOpt.NonNullAndHasErrors())
Debug.Assert(namespaceSymbol IsNot Nothing, "Field 'namespaceSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnevaluatedReceiverOpt = unevaluatedReceiverOpt
Me._AliasOpt = aliasOpt
Me._NamespaceSymbol = namespaceSymbol
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _UnevaluatedReceiverOpt As BoundExpression
Public ReadOnly Property UnevaluatedReceiverOpt As BoundExpression
Get
Return _UnevaluatedReceiverOpt
End Get
End Property
Private ReadOnly _AliasOpt As AliasSymbol
Public ReadOnly Property AliasOpt As AliasSymbol
Get
Return _AliasOpt
End Get
End Property
Private ReadOnly _NamespaceSymbol As NamespaceSymbol
Public ReadOnly Property NamespaceSymbol As NamespaceSymbol
Get
Return _NamespaceSymbol
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNamespaceExpression(Me)
End Function
Public Function Update(unevaluatedReceiverOpt As BoundExpression, aliasOpt As AliasSymbol, namespaceSymbol As NamespaceSymbol) As BoundNamespaceExpression
If unevaluatedReceiverOpt IsNot Me.UnevaluatedReceiverOpt OrElse aliasOpt IsNot Me.AliasOpt OrElse namespaceSymbol IsNot Me.NamespaceSymbol Then
Dim result = New BoundNamespaceExpression(Me.Syntax, unevaluatedReceiverOpt, aliasOpt, namespaceSymbol, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMethodDefIndex
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MethodDefIndex, syntax, type, hasErrors)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, type As TypeSymbol)
MyBase.New(BoundKind.MethodDefIndex, syntax, type)
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
End Sub
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMethodDefIndex(Me)
End Function
Public Function Update(method As MethodSymbol, type As TypeSymbol) As BoundMethodDefIndex
If method IsNot Me.Method OrElse type IsNot Me.Type Then
Dim result = New BoundMethodDefIndex(Me.Syntax, method, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMaximumMethodDefIndex
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MaximumMethodDefIndex, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MaximumMethodDefIndex, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMaximumMethodDefIndex(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMaximumMethodDefIndex
If type IsNot Me.Type Then
Dim result = New BoundMaximumMethodDefIndex(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundInstrumentationPayloadRoot
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, analysisKind As Integer, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.InstrumentationPayloadRoot, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._AnalysisKind = analysisKind
Me._IsLValue = isLValue
End Sub
Public Sub New(syntax As SyntaxNode, analysisKind As Integer, isLValue As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.InstrumentationPayloadRoot, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._AnalysisKind = analysisKind
Me._IsLValue = isLValue
End Sub
Private ReadOnly _AnalysisKind As Integer
Public ReadOnly Property AnalysisKind As Integer
Get
Return _AnalysisKind
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInstrumentationPayloadRoot(Me)
End Function
Public Function Update(analysisKind As Integer, isLValue As Boolean, type As TypeSymbol) As BoundInstrumentationPayloadRoot
If analysisKind <> Me.AnalysisKind OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundInstrumentationPayloadRoot(Me.Syntax, analysisKind, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundModuleVersionId
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ModuleVersionId, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsLValue = isLValue
End Sub
Public Sub New(syntax As SyntaxNode, isLValue As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.ModuleVersionId, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsLValue = isLValue
End Sub
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitModuleVersionId(Me)
End Function
Public Function Update(isLValue As Boolean, type As TypeSymbol) As BoundModuleVersionId
If isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundModuleVersionId(Me.Syntax, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundModuleVersionIdString
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ModuleVersionIdString, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.ModuleVersionIdString, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitModuleVersionIdString(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundModuleVersionIdString
If type IsNot Me.Type Then
Dim result = New BoundModuleVersionIdString(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSourceDocumentIndex
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, document As Cci.DebugSourceDocument, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.SourceDocumentIndex, syntax, type, hasErrors)
Debug.Assert(document IsNot Nothing, "Field 'document' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Document = document
End Sub
Public Sub New(syntax As SyntaxNode, document As Cci.DebugSourceDocument, type As TypeSymbol)
MyBase.New(BoundKind.SourceDocumentIndex, syntax, type)
Debug.Assert(document IsNot Nothing, "Field 'document' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Document = document
End Sub
Private ReadOnly _Document As Cci.DebugSourceDocument
Public ReadOnly Property Document As Cci.DebugSourceDocument
Get
Return _Document
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSourceDocumentIndex(Me)
End Function
Public Function Update(document As Cci.DebugSourceDocument, type As TypeSymbol) As BoundSourceDocumentIndex
If document IsNot Me.Document OrElse type IsNot Me.Type Then
Dim result = New BoundSourceDocumentIndex(Me.Syntax, document, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As UnaryOperatorKind, operand As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnaryOperator, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._Operand = operand
Me._Checked = checked
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As UnaryOperatorKind
Public ReadOnly Property OperatorKind As UnaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnaryOperator(Me)
End Function
Public Function Update(operatorKind As UnaryOperatorKind, operand As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundUnaryOperator
If operatorKind <> Me.OperatorKind OrElse operand IsNot Me.Operand OrElse checked <> Me.Checked OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundUnaryOperator(Me.Syntax, operatorKind, operand, checked, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedUnaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As UnaryOperatorKind, underlyingExpression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedUnaryOperator, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._UnderlyingExpression = underlyingExpression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As UnaryOperatorKind
Public ReadOnly Property OperatorKind As UnaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedUnaryOperator(Me)
End Function
Public Function Update(operatorKind As UnaryOperatorKind, underlyingExpression As BoundExpression, type As TypeSymbol) As BoundUserDefinedUnaryOperator
If operatorKind <> Me.OperatorKind OrElse underlyingExpression IsNot Me.UnderlyingExpression OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedUnaryOperator(Me.Syntax, operatorKind, underlyingExpression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNullableIsTrueOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NullableIsTrueOperator, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNullableIsTrueOperator(Me)
End Function
Public Function Update(operand As BoundExpression, type As TypeSymbol) As BoundNullableIsTrueOperator
If operand IsNot Me.Operand OrElse type IsNot Me.Type Then
Dim result = New BoundNullableIsTrueOperator(Me.Syntax, operand, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBinaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BinaryOperator, syntax, type, hasErrors OrElse left.NonNullAndHasErrors() OrElse right.NonNullAndHasErrors())
Debug.Assert(left IsNot Nothing, "Field 'left' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(right IsNot Nothing, "Field 'right' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._Left = left
Me._Right = right
Me._Checked = checked
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As BinaryOperatorKind
Public ReadOnly Property OperatorKind As BinaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _Left As BoundExpression
Public ReadOnly Property Left As BoundExpression
Get
Return _Left
End Get
End Property
Private ReadOnly _Right As BoundExpression
Public ReadOnly Property Right As BoundExpression
Get
Return _Right
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBinaryOperator(Me)
End Function
Public Function Update(operatorKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, checked As Boolean, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundBinaryOperator
If operatorKind <> Me.OperatorKind OrElse left IsNot Me.Left OrElse right IsNot Me.Right OrElse checked <> Me.Checked OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundBinaryOperator(Me.Syntax, operatorKind, left, right, checked, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedBinaryOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operatorKind As BinaryOperatorKind, underlyingExpression As BoundExpression, checked As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedBinaryOperator, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OperatorKind = operatorKind
Me._UnderlyingExpression = underlyingExpression
Me._Checked = checked
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As BinaryOperatorKind
Public ReadOnly Property OperatorKind As BinaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedBinaryOperator(Me)
End Function
Public Function Update(operatorKind As BinaryOperatorKind, underlyingExpression As BoundExpression, checked As Boolean, type As TypeSymbol) As BoundUserDefinedBinaryOperator
If operatorKind <> Me.OperatorKind OrElse underlyingExpression IsNot Me.UnderlyingExpression OrElse checked <> Me.Checked OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedBinaryOperator(Me.Syntax, operatorKind, underlyingExpression, checked, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedShortCircuitingOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, leftOperand As BoundExpression, leftOperandPlaceholder As BoundRValuePlaceholder, leftTest As BoundExpression, bitwiseOperator As BoundUserDefinedBinaryOperator, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedShortCircuitingOperator, syntax, type, hasErrors OrElse leftOperand.NonNullAndHasErrors() OrElse leftOperandPlaceholder.NonNullAndHasErrors() OrElse leftTest.NonNullAndHasErrors() OrElse bitwiseOperator.NonNullAndHasErrors())
Debug.Assert(bitwiseOperator IsNot Nothing, "Field 'bitwiseOperator' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LeftOperand = leftOperand
Me._LeftOperandPlaceholder = leftOperandPlaceholder
Me._LeftTest = leftTest
Me._BitwiseOperator = bitwiseOperator
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LeftOperand As BoundExpression
Public ReadOnly Property LeftOperand As BoundExpression
Get
Return _LeftOperand
End Get
End Property
Private ReadOnly _LeftOperandPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property LeftOperandPlaceholder As BoundRValuePlaceholder
Get
Return _LeftOperandPlaceholder
End Get
End Property
Private ReadOnly _LeftTest As BoundExpression
Public ReadOnly Property LeftTest As BoundExpression
Get
Return _LeftTest
End Get
End Property
Private ReadOnly _BitwiseOperator As BoundUserDefinedBinaryOperator
Public ReadOnly Property BitwiseOperator As BoundUserDefinedBinaryOperator
Get
Return _BitwiseOperator
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedShortCircuitingOperator(Me)
End Function
Public Function Update(leftOperand As BoundExpression, leftOperandPlaceholder As BoundRValuePlaceholder, leftTest As BoundExpression, bitwiseOperator As BoundUserDefinedBinaryOperator, type As TypeSymbol) As BoundUserDefinedShortCircuitingOperator
If leftOperand IsNot Me.LeftOperand OrElse leftOperandPlaceholder IsNot Me.LeftOperandPlaceholder OrElse leftTest IsNot Me.LeftTest OrElse bitwiseOperator IsNot Me.BitwiseOperator OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedShortCircuitingOperator(Me.Syntax, leftOperand, leftOperandPlaceholder, leftTest, bitwiseOperator, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCompoundAssignmentTargetPlaceholder
Inherits BoundValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.CompoundAssignmentTargetPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.CompoundAssignmentTargetPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCompoundAssignmentTargetPlaceholder(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundCompoundAssignmentTargetPlaceholder
If type IsNot Me.Type Then
Dim result = New BoundCompoundAssignmentTargetPlaceholder(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAssignmentOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, left As BoundExpression, leftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder, right As BoundExpression, suppressObjectClone As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AssignmentOperator, syntax, type, hasErrors OrElse left.NonNullAndHasErrors() OrElse leftOnTheRightOpt.NonNullAndHasErrors() OrElse right.NonNullAndHasErrors())
Debug.Assert(left IsNot Nothing, "Field 'left' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(right IsNot Nothing, "Field 'right' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Left = left
Me._LeftOnTheRightOpt = leftOnTheRightOpt
Me._Right = right
Me._SuppressObjectClone = suppressObjectClone
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Left As BoundExpression
Public ReadOnly Property Left As BoundExpression
Get
Return _Left
End Get
End Property
Private ReadOnly _LeftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder
Public ReadOnly Property LeftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder
Get
Return _LeftOnTheRightOpt
End Get
End Property
Private ReadOnly _Right As BoundExpression
Public ReadOnly Property Right As BoundExpression
Get
Return _Right
End Get
End Property
Private ReadOnly _SuppressObjectClone As Boolean
Public ReadOnly Property SuppressObjectClone As Boolean
Get
Return _SuppressObjectClone
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAssignmentOperator(Me)
End Function
Public Function Update(left As BoundExpression, leftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder, right As BoundExpression, suppressObjectClone As Boolean, type As TypeSymbol) As BoundAssignmentOperator
If left IsNot Me.Left OrElse leftOnTheRightOpt IsNot Me.LeftOnTheRightOpt OrElse right IsNot Me.Right OrElse suppressObjectClone <> Me.SuppressObjectClone OrElse type IsNot Me.Type Then
Dim result = New BoundAssignmentOperator(Me.Syntax, left, leftOnTheRightOpt, right, suppressObjectClone, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundReferenceAssignment
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, byRefLocal As BoundLocal, lValue As BoundExpression, isLValue As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ReferenceAssignment, syntax, type, hasErrors OrElse byRefLocal.NonNullAndHasErrors() OrElse lValue.NonNullAndHasErrors())
Debug.Assert(byRefLocal IsNot Nothing, "Field 'byRefLocal' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ByRefLocal = byRefLocal
Me._LValue = lValue
Me._IsLValue = isLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ByRefLocal As BoundLocal
Public ReadOnly Property ByRefLocal As BoundLocal
Get
Return _ByRefLocal
End Get
End Property
Private ReadOnly _LValue As BoundExpression
Public ReadOnly Property LValue As BoundExpression
Get
Return _LValue
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitReferenceAssignment(Me)
End Function
Public Function Update(byRefLocal As BoundLocal, lValue As BoundExpression, isLValue As Boolean, type As TypeSymbol) As BoundReferenceAssignment
If byRefLocal IsNot Me.ByRefLocal OrElse lValue IsNot Me.LValue OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundReferenceAssignment(Me.Syntax, byRefLocal, lValue, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAddressOfOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, withDependencies As Boolean, methodGroup As BoundMethodGroup, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AddressOfOperator, syntax, Nothing, hasErrors OrElse methodGroup.NonNullAndHasErrors())
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(methodGroup IsNot Nothing, "Field 'methodGroup' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._WithDependencies = withDependencies
Me._MethodGroup = methodGroup
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _WithDependencies As Boolean
Public ReadOnly Property WithDependencies As Boolean
Get
Return _WithDependencies
End Get
End Property
Private ReadOnly _MethodGroup As BoundMethodGroup
Public ReadOnly Property MethodGroup As BoundMethodGroup
Get
Return _MethodGroup
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAddressOfOperator(Me)
End Function
Public Function Update(binder As Binder, withDependencies As Boolean, methodGroup As BoundMethodGroup) As BoundAddressOfOperator
If binder IsNot Me.Binder OrElse withDependencies <> Me.WithDependencies OrElse methodGroup IsNot Me.MethodGroup Then
Dim result = New BoundAddressOfOperator(Me.Syntax, binder, withDependencies, methodGroup, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTernaryConditionalExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, whenTrue As BoundExpression, whenFalse As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TernaryConditionalExpression, syntax, type, hasErrors OrElse condition.NonNullAndHasErrors() OrElse whenTrue.NonNullAndHasErrors() OrElse whenFalse.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(whenTrue IsNot Nothing, "Field 'whenTrue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(whenFalse IsNot Nothing, "Field 'whenFalse' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._WhenTrue = whenTrue
Me._WhenFalse = whenFalse
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _WhenTrue As BoundExpression
Public ReadOnly Property WhenTrue As BoundExpression
Get
Return _WhenTrue
End Get
End Property
Private ReadOnly _WhenFalse As BoundExpression
Public ReadOnly Property WhenFalse As BoundExpression
Get
Return _WhenFalse
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTernaryConditionalExpression(Me)
End Function
Public Function Update(condition As BoundExpression, whenTrue As BoundExpression, whenFalse As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundTernaryConditionalExpression
If condition IsNot Me.Condition OrElse whenTrue IsNot Me.WhenTrue OrElse whenFalse IsNot Me.WhenFalse OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundTernaryConditionalExpression(Me.Syntax, condition, whenTrue, whenFalse, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBinaryConditionalExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, testExpression As BoundExpression, convertedTestExpression As BoundExpression, testExpressionPlaceholder As BoundRValuePlaceholder, elseExpression As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.BinaryConditionalExpression, syntax, type, hasErrors OrElse testExpression.NonNullAndHasErrors() OrElse convertedTestExpression.NonNullAndHasErrors() OrElse testExpressionPlaceholder.NonNullAndHasErrors() OrElse elseExpression.NonNullAndHasErrors())
Debug.Assert(testExpression IsNot Nothing, "Field 'testExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(elseExpression IsNot Nothing, "Field 'elseExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TestExpression = testExpression
Me._ConvertedTestExpression = convertedTestExpression
Me._TestExpressionPlaceholder = testExpressionPlaceholder
Me._ElseExpression = elseExpression
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _TestExpression As BoundExpression
Public ReadOnly Property TestExpression As BoundExpression
Get
Return _TestExpression
End Get
End Property
Private ReadOnly _ConvertedTestExpression As BoundExpression
Public ReadOnly Property ConvertedTestExpression As BoundExpression
Get
Return _ConvertedTestExpression
End Get
End Property
Private ReadOnly _TestExpressionPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property TestExpressionPlaceholder As BoundRValuePlaceholder
Get
Return _TestExpressionPlaceholder
End Get
End Property
Private ReadOnly _ElseExpression As BoundExpression
Public ReadOnly Property ElseExpression As BoundExpression
Get
Return _ElseExpression
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBinaryConditionalExpression(Me)
End Function
Public Function Update(testExpression As BoundExpression, convertedTestExpression As BoundExpression, testExpressionPlaceholder As BoundRValuePlaceholder, elseExpression As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundBinaryConditionalExpression
If testExpression IsNot Me.TestExpression OrElse convertedTestExpression IsNot Me.ConvertedTestExpression OrElse testExpressionPlaceholder IsNot Me.TestExpressionPlaceholder OrElse elseExpression IsNot Me.ElseExpression OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundBinaryConditionalExpression(Me.Syntax, testExpression, convertedTestExpression, testExpressionPlaceholder, elseExpression, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundConversionOrCast
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundConversion
Inherits BoundConversionOrCast
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, checked As Boolean, explicitCastInCode As Boolean, constantValueOpt As ConstantValue, extendedInfoOpt As BoundExtendedConversionInfo, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Conversion, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse extendedInfoOpt.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._ConversionKind = conversionKind
Me._Checked = checked
Me._ExplicitCastInCode = explicitCastInCode
Me._ConstantValueOpt = constantValueOpt
Me._ExtendedInfoOpt = extendedInfoOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public Overrides ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _ConversionKind As ConversionKind
Public Overrides ReadOnly Property ConversionKind As ConversionKind
Get
Return _ConversionKind
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _ExplicitCastInCode As Boolean
Public Overrides ReadOnly Property ExplicitCastInCode As Boolean
Get
Return _ExplicitCastInCode
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _ExtendedInfoOpt As BoundExtendedConversionInfo
Public ReadOnly Property ExtendedInfoOpt As BoundExtendedConversionInfo
Get
Return _ExtendedInfoOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConversion(Me)
End Function
Public Function Update(operand As BoundExpression, conversionKind As ConversionKind, checked As Boolean, explicitCastInCode As Boolean, constantValueOpt As ConstantValue, extendedInfoOpt As BoundExtendedConversionInfo, type As TypeSymbol) As BoundConversion
If operand IsNot Me.Operand OrElse conversionKind <> Me.ConversionKind OrElse checked <> Me.Checked OrElse explicitCastInCode <> Me.ExplicitCastInCode OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse extendedInfoOpt IsNot Me.ExtendedInfoOpt OrElse type IsNot Me.Type Then
Dim result = New BoundConversion(Me.Syntax, operand, conversionKind, checked, explicitCastInCode, constantValueOpt, extendedInfoOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundExtendedConversionInfo
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend NotInheritable Class BoundRelaxationLambda
Inherits BoundExtendedConversionInfo
Public Sub New(syntax As SyntaxNode, lambda As BoundLambda, receiverPlaceholderOpt As BoundRValuePlaceholder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RelaxationLambda, syntax, hasErrors OrElse lambda.NonNullAndHasErrors() OrElse receiverPlaceholderOpt.NonNullAndHasErrors())
Debug.Assert(lambda IsNot Nothing, "Field 'lambda' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Lambda = lambda
Me._ReceiverPlaceholderOpt = receiverPlaceholderOpt
End Sub
Private ReadOnly _Lambda As BoundLambda
Public ReadOnly Property Lambda As BoundLambda
Get
Return _Lambda
End Get
End Property
Private ReadOnly _ReceiverPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property ReceiverPlaceholderOpt As BoundRValuePlaceholder
Get
Return _ReceiverPlaceholderOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRelaxationLambda(Me)
End Function
Public Function Update(lambda As BoundLambda, receiverPlaceholderOpt As BoundRValuePlaceholder) As BoundRelaxationLambda
If lambda IsNot Me.Lambda OrElse receiverPlaceholderOpt IsNot Me.ReceiverPlaceholderOpt Then
Dim result = New BoundRelaxationLambda(Me.Syntax, lambda, receiverPlaceholderOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConvertedTupleElements
Inherits BoundExtendedConversionInfo
Public Sub New(syntax As SyntaxNode, elementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder), convertedElements As ImmutableArray(Of BoundExpression), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConvertedTupleElements, syntax, hasErrors OrElse elementPlaceholders.NonNullAndHasErrors() OrElse convertedElements.NonNullAndHasErrors())
Debug.Assert(Not (elementPlaceholders.IsDefault), "Field 'elementPlaceholders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (convertedElements.IsDefault), "Field 'convertedElements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ElementPlaceholders = elementPlaceholders
Me._ConvertedElements = convertedElements
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ElementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder)
Public ReadOnly Property ElementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder)
Get
Return _ElementPlaceholders
End Get
End Property
Private ReadOnly _ConvertedElements As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ConvertedElements As ImmutableArray(Of BoundExpression)
Get
Return _ConvertedElements
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConvertedTupleElements(Me)
End Function
Public Function Update(elementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder), convertedElements As ImmutableArray(Of BoundExpression)) As BoundConvertedTupleElements
If elementPlaceholders <> Me.ElementPlaceholders OrElse convertedElements <> Me.ConvertedElements Then
Dim result = New BoundConvertedTupleElements(Me.Syntax, elementPlaceholders, convertedElements, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUserDefinedConversion
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, underlyingExpression As BoundExpression, inOutConversionFlags As Byte, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UserDefinedConversion, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingExpression = underlyingExpression
Me._InOutConversionFlags = inOutConversionFlags
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
Private ReadOnly _InOutConversionFlags As Byte
Public ReadOnly Property InOutConversionFlags As Byte
Get
Return _InOutConversionFlags
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUserDefinedConversion(Me)
End Function
Public Function Update(underlyingExpression As BoundExpression, inOutConversionFlags As Byte, type As TypeSymbol) As BoundUserDefinedConversion
If underlyingExpression IsNot Me.UnderlyingExpression OrElse inOutConversionFlags <> Me.InOutConversionFlags OrElse type IsNot Me.Type Then
Dim result = New BoundUserDefinedConversion(Me.Syntax, underlyingExpression, inOutConversionFlags, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDirectCast
Inherits BoundConversionOrCast
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, suppressVirtualCalls As Boolean, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DirectCast, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse relaxationLambdaOpt.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._ConversionKind = conversionKind
Me._SuppressVirtualCalls = suppressVirtualCalls
Me._ConstantValueOpt = constantValueOpt
Me._RelaxationLambdaOpt = relaxationLambdaOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public Overrides ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _ConversionKind As ConversionKind
Public Overrides ReadOnly Property ConversionKind As ConversionKind
Get
Return _ConversionKind
End Get
End Property
Private ReadOnly _SuppressVirtualCalls As Boolean
Public Overrides ReadOnly Property SuppressVirtualCalls As Boolean
Get
Return _SuppressVirtualCalls
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _RelaxationLambdaOpt As BoundLambda
Public ReadOnly Property RelaxationLambdaOpt As BoundLambda
Get
Return _RelaxationLambdaOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDirectCast(Me)
End Function
Public Function Update(operand As BoundExpression, conversionKind As ConversionKind, suppressVirtualCalls As Boolean, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol) As BoundDirectCast
If operand IsNot Me.Operand OrElse conversionKind <> Me.ConversionKind OrElse suppressVirtualCalls <> Me.SuppressVirtualCalls OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse relaxationLambdaOpt IsNot Me.RelaxationLambdaOpt OrElse type IsNot Me.Type Then
Dim result = New BoundDirectCast(Me.Syntax, operand, conversionKind, suppressVirtualCalls, constantValueOpt, relaxationLambdaOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTryCast
Inherits BoundConversionOrCast
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, conversionKind As ConversionKind, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TryCast, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse relaxationLambdaOpt.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._ConversionKind = conversionKind
Me._ConstantValueOpt = constantValueOpt
Me._RelaxationLambdaOpt = relaxationLambdaOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public Overrides ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _ConversionKind As ConversionKind
Public Overrides ReadOnly Property ConversionKind As ConversionKind
Get
Return _ConversionKind
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _RelaxationLambdaOpt As BoundLambda
Public ReadOnly Property RelaxationLambdaOpt As BoundLambda
Get
Return _RelaxationLambdaOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTryCast(Me)
End Function
Public Function Update(operand As BoundExpression, conversionKind As ConversionKind, constantValueOpt As ConstantValue, relaxationLambdaOpt As BoundLambda, type As TypeSymbol) As BoundTryCast
If operand IsNot Me.Operand OrElse conversionKind <> Me.ConversionKind OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse relaxationLambdaOpt IsNot Me.RelaxationLambdaOpt OrElse type IsNot Me.Type Then
Dim result = New BoundTryCast(Me.Syntax, operand, conversionKind, constantValueOpt, relaxationLambdaOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeOf
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, isTypeOfIsNotExpression As Boolean, targetType As TypeSymbol, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TypeOf, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(targetType IsNot Nothing, "Field 'targetType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._IsTypeOfIsNotExpression = isTypeOfIsNotExpression
Me._TargetType = targetType
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _IsTypeOfIsNotExpression As Boolean
Public ReadOnly Property IsTypeOfIsNotExpression As Boolean
Get
Return _IsTypeOfIsNotExpression
End Get
End Property
Private ReadOnly _TargetType As TypeSymbol
Public ReadOnly Property TargetType As TypeSymbol
Get
Return _TargetType
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeOf(Me)
End Function
Public Function Update(operand As BoundExpression, isTypeOfIsNotExpression As Boolean, targetType As TypeSymbol, type As TypeSymbol) As BoundTypeOf
If operand IsNot Me.Operand OrElse isTypeOfIsNotExpression <> Me.IsTypeOfIsNotExpression OrElse targetType IsNot Me.TargetType OrElse type IsNot Me.Type Then
Dim result = New BoundTypeOf(Me.Syntax, operand, isTypeOfIsNotExpression, targetType, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundStatement
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend NotInheritable Class BoundSequencePoint
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statementOpt As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SequencePoint, syntax, hasErrors OrElse statementOpt.NonNullAndHasErrors())
Me._StatementOpt = statementOpt
End Sub
Private ReadOnly _StatementOpt As BoundStatement
Public ReadOnly Property StatementOpt As BoundStatement
Get
Return _StatementOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequencePoint(Me)
End Function
Public Function Update(statementOpt As BoundStatement) As BoundSequencePoint
If statementOpt IsNot Me.StatementOpt Then
Dim result = New BoundSequencePoint(Me.Syntax, statementOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSequencePointExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SequencePointExpression, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequencePointExpression(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundSequencePointExpression
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundSequencePointExpression(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSequencePointWithSpan
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statementOpt As BoundStatement, span As TextSpan, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SequencePointWithSpan, syntax, hasErrors OrElse statementOpt.NonNullAndHasErrors())
Me._StatementOpt = statementOpt
Me._Span = span
End Sub
Private ReadOnly _StatementOpt As BoundStatement
Public ReadOnly Property StatementOpt As BoundStatement
Get
Return _StatementOpt
End Get
End Property
Private ReadOnly _Span As TextSpan
Public ReadOnly Property Span As TextSpan
Get
Return _Span
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequencePointWithSpan(Me)
End Function
Public Function Update(statementOpt As BoundStatement, span As TextSpan) As BoundSequencePointWithSpan
If statementOpt IsNot Me.StatementOpt OrElse span <> Me.Span Then
Dim result = New BoundSequencePointWithSpan(Me.Syntax, statementOpt, span, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNoOpStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, flavor As NoOpStatementFlavor, hasErrors As Boolean)
MyBase.New(BoundKind.NoOpStatement, syntax, hasErrors)
Me._Flavor = flavor
End Sub
Public Sub New(syntax As SyntaxNode, flavor As NoOpStatementFlavor)
MyBase.New(BoundKind.NoOpStatement, syntax)
Me._Flavor = flavor
End Sub
Private ReadOnly _Flavor As NoOpStatementFlavor
Public ReadOnly Property Flavor As NoOpStatementFlavor
Get
Return _Flavor
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNoOpStatement(Me)
End Function
Public Function Update(flavor As NoOpStatementFlavor) As BoundNoOpStatement
If flavor <> Me.Flavor Then
Dim result = New BoundNoOpStatement(Me.Syntax, flavor, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundMethodOrPropertyGroup
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, Nothing, hasErrors)
Me._ReceiverOpt = receiverOpt
Me._QualificationKind = qualificationKind
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _QualificationKind As QualificationKind
Public ReadOnly Property QualificationKind As QualificationKind
Get
Return _QualificationKind
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundMethodGroup
Inherits BoundMethodOrPropertyGroup
Public Sub New(syntax As SyntaxNode, typeArgumentsOpt As BoundTypeArguments, methods As ImmutableArray(Of MethodSymbol), pendingExtensionMethodsOpt As ExtensionMethodGroup, resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.MethodGroup, syntax, receiverOpt, qualificationKind, hasErrors OrElse typeArgumentsOpt.NonNullAndHasErrors() OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(Not (methods.IsDefault), "Field 'methods' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TypeArgumentsOpt = typeArgumentsOpt
Me._Methods = methods
Me._PendingExtensionMethodsOpt = pendingExtensionMethodsOpt
Me._ResultKind = resultKind
End Sub
Private ReadOnly _TypeArgumentsOpt As BoundTypeArguments
Public ReadOnly Property TypeArgumentsOpt As BoundTypeArguments
Get
Return _TypeArgumentsOpt
End Get
End Property
Private ReadOnly _Methods As ImmutableArray(Of MethodSymbol)
Public ReadOnly Property Methods As ImmutableArray(Of MethodSymbol)
Get
Return _Methods
End Get
End Property
Private ReadOnly _PendingExtensionMethodsOpt As ExtensionMethodGroup
Public ReadOnly Property PendingExtensionMethodsOpt As ExtensionMethodGroup
Get
Return _PendingExtensionMethodsOpt
End Get
End Property
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMethodGroup(Me)
End Function
Public Function Update(typeArgumentsOpt As BoundTypeArguments, methods As ImmutableArray(Of MethodSymbol), pendingExtensionMethodsOpt As ExtensionMethodGroup, resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind) As BoundMethodGroup
If typeArgumentsOpt IsNot Me.TypeArgumentsOpt OrElse methods <> Me.Methods OrElse pendingExtensionMethodsOpt IsNot Me.PendingExtensionMethodsOpt OrElse resultKind <> Me.ResultKind OrElse receiverOpt IsNot Me.ReceiverOpt OrElse qualificationKind <> Me.QualificationKind Then
Dim result = New BoundMethodGroup(Me.Syntax, typeArgumentsOpt, methods, pendingExtensionMethodsOpt, resultKind, receiverOpt, qualificationKind, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPropertyGroup
Inherits BoundMethodOrPropertyGroup
Public Sub New(syntax As SyntaxNode, properties As ImmutableArray(Of PropertySymbol), resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.PropertyGroup, syntax, receiverOpt, qualificationKind, hasErrors OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(Not (properties.IsDefault), "Field 'properties' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Properties = properties
Me._ResultKind = resultKind
End Sub
Private ReadOnly _Properties As ImmutableArray(Of PropertySymbol)
Public ReadOnly Property Properties As ImmutableArray(Of PropertySymbol)
Get
Return _Properties
End Get
End Property
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPropertyGroup(Me)
End Function
Public Function Update(properties As ImmutableArray(Of PropertySymbol), resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind) As BoundPropertyGroup
If properties <> Me.Properties OrElse resultKind <> Me.ResultKind OrElse receiverOpt IsNot Me.ReceiverOpt OrElse qualificationKind <> Me.QualificationKind Then
Dim result = New BoundPropertyGroup(Me.Syntax, properties, resultKind, receiverOpt, qualificationKind, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundReturnStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expressionOpt As BoundExpression, functionLocalOpt As LocalSymbol, exitLabelOpt As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ReturnStatement, syntax, hasErrors OrElse expressionOpt.NonNullAndHasErrors())
Me._ExpressionOpt = expressionOpt
Me._FunctionLocalOpt = functionLocalOpt
Me._ExitLabelOpt = exitLabelOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ExpressionOpt As BoundExpression
Public ReadOnly Property ExpressionOpt As BoundExpression
Get
Return _ExpressionOpt
End Get
End Property
Private ReadOnly _FunctionLocalOpt As LocalSymbol
Public ReadOnly Property FunctionLocalOpt As LocalSymbol
Get
Return _FunctionLocalOpt
End Get
End Property
Private ReadOnly _ExitLabelOpt As LabelSymbol
Public ReadOnly Property ExitLabelOpt As LabelSymbol
Get
Return _ExitLabelOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitReturnStatement(Me)
End Function
Public Function Update(expressionOpt As BoundExpression, functionLocalOpt As LocalSymbol, exitLabelOpt As LabelSymbol) As BoundReturnStatement
If expressionOpt IsNot Me.ExpressionOpt OrElse functionLocalOpt IsNot Me.FunctionLocalOpt OrElse exitLabelOpt IsNot Me.ExitLabelOpt Then
Dim result = New BoundReturnStatement(Me.Syntax, expressionOpt, functionLocalOpt, exitLabelOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundYieldStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.YieldStatement, syntax, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitYieldStatement(Me)
End Function
Public Function Update(expression As BoundExpression) As BoundYieldStatement
If expression IsNot Me.Expression Then
Dim result = New BoundYieldStatement(Me.Syntax, expression, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundThrowStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expressionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ThrowStatement, syntax, hasErrors OrElse expressionOpt.NonNullAndHasErrors())
Me._ExpressionOpt = expressionOpt
End Sub
Private ReadOnly _ExpressionOpt As BoundExpression
Public ReadOnly Property ExpressionOpt As BoundExpression
Get
Return _ExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitThrowStatement(Me)
End Function
Public Function Update(expressionOpt As BoundExpression) As BoundThrowStatement
If expressionOpt IsNot Me.ExpressionOpt Then
Dim result = New BoundThrowStatement(Me.Syntax, expressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRedimStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, clauses As ImmutableArray(Of BoundRedimClause), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RedimStatement, syntax, hasErrors OrElse clauses.NonNullAndHasErrors())
Debug.Assert(Not (clauses.IsDefault), "Field 'clauses' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Clauses = clauses
End Sub
Private ReadOnly _Clauses As ImmutableArray(Of BoundRedimClause)
Public ReadOnly Property Clauses As ImmutableArray(Of BoundRedimClause)
Get
Return _Clauses
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRedimStatement(Me)
End Function
Public Function Update(clauses As ImmutableArray(Of BoundRedimClause)) As BoundRedimStatement
If clauses <> Me.Clauses Then
Dim result = New BoundRedimStatement(Me.Syntax, clauses, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRedimClause
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, indices As ImmutableArray(Of BoundExpression), arrayTypeOpt As ArrayTypeSymbol, preserve As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RedimClause, syntax, hasErrors OrElse operand.NonNullAndHasErrors() OrElse indices.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (indices.IsDefault), "Field 'indices' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._Indices = indices
Me._ArrayTypeOpt = arrayTypeOpt
Me._Preserve = preserve
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _Indices As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Indices As ImmutableArray(Of BoundExpression)
Get
Return _Indices
End Get
End Property
Private ReadOnly _ArrayTypeOpt As ArrayTypeSymbol
Public ReadOnly Property ArrayTypeOpt As ArrayTypeSymbol
Get
Return _ArrayTypeOpt
End Get
End Property
Private ReadOnly _Preserve As Boolean
Public ReadOnly Property Preserve As Boolean
Get
Return _Preserve
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRedimClause(Me)
End Function
Public Function Update(operand As BoundExpression, indices As ImmutableArray(Of BoundExpression), arrayTypeOpt As ArrayTypeSymbol, preserve As Boolean) As BoundRedimClause
If operand IsNot Me.Operand OrElse indices <> Me.Indices OrElse arrayTypeOpt IsNot Me.ArrayTypeOpt OrElse preserve <> Me.Preserve Then
Dim result = New BoundRedimClause(Me.Syntax, operand, indices, arrayTypeOpt, preserve, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundEraseStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, clauses As ImmutableArray(Of BoundAssignmentOperator), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.EraseStatement, syntax, hasErrors OrElse clauses.NonNullAndHasErrors())
Debug.Assert(Not (clauses.IsDefault), "Field 'clauses' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Clauses = clauses
End Sub
Private ReadOnly _Clauses As ImmutableArray(Of BoundAssignmentOperator)
Public ReadOnly Property Clauses As ImmutableArray(Of BoundAssignmentOperator)
Get
Return _Clauses
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitEraseStatement(Me)
End Function
Public Function Update(clauses As ImmutableArray(Of BoundAssignmentOperator)) As BoundEraseStatement
If clauses <> Me.Clauses Then
Dim result = New BoundEraseStatement(Me.Syntax, clauses, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCall
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, method As MethodSymbol, methodGroupOpt As BoundMethodGroup, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, constantValueOpt As ConstantValue, isLValue As Boolean, suppressObjectClone As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Call, syntax, type, hasErrors OrElse methodGroupOpt.NonNullAndHasErrors() OrElse receiverOpt.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors())
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Method = method
Me._MethodGroupOpt = methodGroupOpt
Me._ReceiverOpt = receiverOpt
Me._Arguments = arguments
Me._DefaultArguments = defaultArguments
Me._ConstantValueOpt = constantValueOpt
Me._IsLValue = isLValue
Me._SuppressObjectClone = suppressObjectClone
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
Private ReadOnly _MethodGroupOpt As BoundMethodGroup
Public ReadOnly Property MethodGroupOpt As BoundMethodGroup
Get
Return _MethodGroupOpt
End Get
End Property
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
Private ReadOnly _DefaultArguments As BitVector
Public ReadOnly Property DefaultArguments As BitVector
Get
Return _DefaultArguments
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _SuppressObjectClone As Boolean
Public ReadOnly Property SuppressObjectClone As Boolean
Get
Return _SuppressObjectClone
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCall(Me)
End Function
Public Function Update(method As MethodSymbol, methodGroupOpt As BoundMethodGroup, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, constantValueOpt As ConstantValue, isLValue As Boolean, suppressObjectClone As Boolean, type As TypeSymbol) As BoundCall
If method IsNot Me.Method OrElse methodGroupOpt IsNot Me.MethodGroupOpt OrElse receiverOpt IsNot Me.ReceiverOpt OrElse arguments <> Me.Arguments OrElse defaultArguments <> Me.DefaultArguments OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse isLValue <> Me.IsLValue OrElse suppressObjectClone <> Me.SuppressObjectClone OrElse type IsNot Me.Type Then
Dim result = New BoundCall(Me.Syntax, method, methodGroupOpt, receiverOpt, arguments, defaultArguments, constantValueOpt, isLValue, suppressObjectClone, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAttribute
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, constructor As MethodSymbol, constructorArguments As ImmutableArray(Of BoundExpression), namedArguments As ImmutableArray(Of BoundExpression), resultKind As LookupResultKind, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Attribute, syntax, type, hasErrors OrElse constructorArguments.NonNullAndHasErrors() OrElse namedArguments.NonNullAndHasErrors())
Debug.Assert(Not (constructorArguments.IsDefault), "Field 'constructorArguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (namedArguments.IsDefault), "Field 'namedArguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Constructor = constructor
Me._ConstructorArguments = constructorArguments
Me._NamedArguments = namedArguments
Me._ResultKind = resultKind
End Sub
Private ReadOnly _Constructor As MethodSymbol
Public ReadOnly Property Constructor As MethodSymbol
Get
Return _Constructor
End Get
End Property
Private ReadOnly _ConstructorArguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ConstructorArguments As ImmutableArray(Of BoundExpression)
Get
Return _ConstructorArguments
End Get
End Property
Private ReadOnly _NamedArguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property NamedArguments As ImmutableArray(Of BoundExpression)
Get
Return _NamedArguments
End Get
End Property
Private ReadOnly _ResultKind As LookupResultKind
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return _ResultKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAttribute(Me)
End Function
Public Function Update(constructor As MethodSymbol, constructorArguments As ImmutableArray(Of BoundExpression), namedArguments As ImmutableArray(Of BoundExpression), resultKind As LookupResultKind, type As TypeSymbol) As BoundAttribute
If constructor IsNot Me.Constructor OrElse constructorArguments <> Me.ConstructorArguments OrElse namedArguments <> Me.NamedArguments OrElse resultKind <> Me.ResultKind OrElse type IsNot Me.Type Then
Dim result = New BoundAttribute(Me.Syntax, constructor, constructorArguments, namedArguments, resultKind, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateMemberAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, nameOpt As String, containerTypeOpt As TypeSymbol, receiverOpt As BoundExpression, typeArgumentsOpt As BoundTypeArguments, accessKind As LateBoundAccessKind, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateMemberAccess, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors() OrElse typeArgumentsOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._NameOpt = nameOpt
Me._ContainerTypeOpt = containerTypeOpt
Me._ReceiverOpt = receiverOpt
Me._TypeArgumentsOpt = typeArgumentsOpt
Me._AccessKind = accessKind
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _NameOpt As String
Public ReadOnly Property NameOpt As String
Get
Return _NameOpt
End Get
End Property
Private ReadOnly _ContainerTypeOpt As TypeSymbol
Public ReadOnly Property ContainerTypeOpt As TypeSymbol
Get
Return _ContainerTypeOpt
End Get
End Property
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _TypeArgumentsOpt As BoundTypeArguments
Public ReadOnly Property TypeArgumentsOpt As BoundTypeArguments
Get
Return _TypeArgumentsOpt
End Get
End Property
Private ReadOnly _AccessKind As LateBoundAccessKind
Public ReadOnly Property AccessKind As LateBoundAccessKind
Get
Return _AccessKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateMemberAccess(Me)
End Function
Public Function Update(nameOpt As String, containerTypeOpt As TypeSymbol, receiverOpt As BoundExpression, typeArgumentsOpt As BoundTypeArguments, accessKind As LateBoundAccessKind, type As TypeSymbol) As BoundLateMemberAccess
If nameOpt IsNot Me.NameOpt OrElse containerTypeOpt IsNot Me.ContainerTypeOpt OrElse receiverOpt IsNot Me.ReceiverOpt OrElse typeArgumentsOpt IsNot Me.TypeArgumentsOpt OrElse accessKind <> Me.AccessKind OrElse type IsNot Me.Type Then
Dim result = New BoundLateMemberAccess(Me.Syntax, nameOpt, containerTypeOpt, receiverOpt, typeArgumentsOpt, accessKind, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateInvocation
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, member As BoundExpression, argumentsOpt As ImmutableArray(Of BoundExpression), argumentNamesOpt As ImmutableArray(Of string), accessKind As LateBoundAccessKind, methodOrPropertyGroupOpt As BoundMethodOrPropertyGroup, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateInvocation, syntax, type, hasErrors OrElse member.NonNullAndHasErrors() OrElse argumentsOpt.NonNullAndHasErrors() OrElse methodOrPropertyGroupOpt.NonNullAndHasErrors())
Debug.Assert(member IsNot Nothing, "Field 'member' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Member = member
Me._ArgumentsOpt = argumentsOpt
Me._ArgumentNamesOpt = argumentNamesOpt
Me._AccessKind = accessKind
Me._MethodOrPropertyGroupOpt = methodOrPropertyGroupOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Member As BoundExpression
Public ReadOnly Property Member As BoundExpression
Get
Return _Member
End Get
End Property
Private ReadOnly _ArgumentsOpt As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ArgumentsOpt As ImmutableArray(Of BoundExpression)
Get
Return _ArgumentsOpt
End Get
End Property
Private ReadOnly _ArgumentNamesOpt As ImmutableArray(Of string)
Public ReadOnly Property ArgumentNamesOpt As ImmutableArray(Of string)
Get
Return _ArgumentNamesOpt
End Get
End Property
Private ReadOnly _AccessKind As LateBoundAccessKind
Public ReadOnly Property AccessKind As LateBoundAccessKind
Get
Return _AccessKind
End Get
End Property
Private ReadOnly _MethodOrPropertyGroupOpt As BoundMethodOrPropertyGroup
Public ReadOnly Property MethodOrPropertyGroupOpt As BoundMethodOrPropertyGroup
Get
Return _MethodOrPropertyGroupOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateInvocation(Me)
End Function
Public Function Update(member As BoundExpression, argumentsOpt As ImmutableArray(Of BoundExpression), argumentNamesOpt As ImmutableArray(Of string), accessKind As LateBoundAccessKind, methodOrPropertyGroupOpt As BoundMethodOrPropertyGroup, type As TypeSymbol) As BoundLateInvocation
If member IsNot Me.Member OrElse argumentsOpt <> Me.ArgumentsOpt OrElse argumentNamesOpt <> Me.ArgumentNamesOpt OrElse accessKind <> Me.AccessKind OrElse methodOrPropertyGroupOpt IsNot Me.MethodOrPropertyGroupOpt OrElse type IsNot Me.Type Then
Dim result = New BoundLateInvocation(Me.Syntax, member, argumentsOpt, argumentNamesOpt, accessKind, methodOrPropertyGroupOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateAddressOfOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, memberAccess As BoundLateMemberAccess, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateAddressOfOperator, syntax, type, hasErrors OrElse memberAccess.NonNullAndHasErrors())
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(memberAccess IsNot Nothing, "Field 'memberAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._MemberAccess = memberAccess
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _MemberAccess As BoundLateMemberAccess
Public ReadOnly Property MemberAccess As BoundLateMemberAccess
Get
Return _MemberAccess
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateAddressOfOperator(Me)
End Function
Public Function Update(binder As Binder, memberAccess As BoundLateMemberAccess, type As TypeSymbol) As BoundLateAddressOfOperator
If binder IsNot Me.Binder OrElse memberAccess IsNot Me.MemberAccess OrElse type IsNot Me.Type Then
Dim result = New BoundLateAddressOfOperator(Me.Syntax, binder, memberAccess, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundTupleExpression
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Arguments = arguments
End Sub
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundTupleLiteral
Inherits BoundTupleExpression
Public Sub New(syntax As SyntaxNode, inferredType As TupleTypeSymbol, argumentNamesOpt As ImmutableArray(Of String), inferredNamesOpt As ImmutableArray(Of Boolean), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TupleLiteral, syntax, arguments, type, hasErrors OrElse arguments.NonNullAndHasErrors())
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InferredType = inferredType
Me._ArgumentNamesOpt = argumentNamesOpt
Me._InferredNamesOpt = inferredNamesOpt
End Sub
Private ReadOnly _InferredType As TupleTypeSymbol
Public ReadOnly Property InferredType As TupleTypeSymbol
Get
Return _InferredType
End Get
End Property
Private ReadOnly _ArgumentNamesOpt As ImmutableArray(Of String)
Public ReadOnly Property ArgumentNamesOpt As ImmutableArray(Of String)
Get
Return _ArgumentNamesOpt
End Get
End Property
Private ReadOnly _InferredNamesOpt As ImmutableArray(Of Boolean)
Public ReadOnly Property InferredNamesOpt As ImmutableArray(Of Boolean)
Get
Return _InferredNamesOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTupleLiteral(Me)
End Function
Public Function Update(inferredType As TupleTypeSymbol, argumentNamesOpt As ImmutableArray(Of String), inferredNamesOpt As ImmutableArray(Of Boolean), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundTupleLiteral
If inferredType IsNot Me.InferredType OrElse argumentNamesOpt <> Me.ArgumentNamesOpt OrElse inferredNamesOpt <> Me.InferredNamesOpt OrElse arguments <> Me.Arguments OrElse type IsNot Me.Type Then
Dim result = New BoundTupleLiteral(Me.Syntax, inferredType, argumentNamesOpt, inferredNamesOpt, arguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConvertedTupleLiteral
Inherits BoundTupleExpression
Public Sub New(syntax As SyntaxNode, naturalTypeOpt As TypeSymbol, arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConvertedTupleLiteral, syntax, arguments, type, hasErrors OrElse arguments.NonNullAndHasErrors())
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._NaturalTypeOpt = naturalTypeOpt
End Sub
Private ReadOnly _NaturalTypeOpt As TypeSymbol
Public ReadOnly Property NaturalTypeOpt As TypeSymbol
Get
Return _NaturalTypeOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConvertedTupleLiteral(Me)
End Function
Public Function Update(naturalTypeOpt As TypeSymbol, arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundConvertedTupleLiteral
If naturalTypeOpt IsNot Me.NaturalTypeOpt OrElse arguments <> Me.Arguments OrElse type IsNot Me.Type Then
Dim result = New BoundConvertedTupleLiteral(Me.Syntax, naturalTypeOpt, arguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundObjectCreationExpressionBase
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitializerOpt = initializerOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _InitializerOpt As BoundObjectInitializerExpressionBase
Public ReadOnly Property InitializerOpt As BoundObjectInitializerExpressionBase
Get
Return _InitializerOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundObjectCreationExpression
Inherits BoundObjectCreationExpressionBase
Public Sub New(syntax As SyntaxNode, constructorOpt As MethodSymbol, methodGroupOpt As BoundMethodGroup, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ObjectCreationExpression, syntax, initializerOpt, type, hasErrors OrElse methodGroupOpt.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors() OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ConstructorOpt = constructorOpt
Me._MethodGroupOpt = methodGroupOpt
Me._Arguments = arguments
Me._DefaultArguments = defaultArguments
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ConstructorOpt As MethodSymbol
Public ReadOnly Property ConstructorOpt As MethodSymbol
Get
Return _ConstructorOpt
End Get
End Property
Private ReadOnly _MethodGroupOpt As BoundMethodGroup
Public ReadOnly Property MethodGroupOpt As BoundMethodGroup
Get
Return _MethodGroupOpt
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
Private ReadOnly _DefaultArguments As BitVector
Public ReadOnly Property DefaultArguments As BitVector
Get
Return _DefaultArguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitObjectCreationExpression(Me)
End Function
Public Function Update(constructorOpt As MethodSymbol, methodGroupOpt As BoundMethodGroup, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundObjectCreationExpression
If constructorOpt IsNot Me.ConstructorOpt OrElse methodGroupOpt IsNot Me.MethodGroupOpt OrElse arguments <> Me.Arguments OrElse defaultArguments <> Me.DefaultArguments OrElse initializerOpt IsNot Me.InitializerOpt OrElse type IsNot Me.Type Then
Dim result = New BoundObjectCreationExpression(Me.Syntax, constructorOpt, methodGroupOpt, arguments, defaultArguments, initializerOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNoPiaObjectCreationExpression
Inherits BoundObjectCreationExpressionBase
Public Sub New(syntax As SyntaxNode, guidString As string, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NoPiaObjectCreationExpression, syntax, initializerOpt, type, hasErrors OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._GuidString = guidString
End Sub
Private ReadOnly _GuidString As string
Public ReadOnly Property GuidString As string
Get
Return _GuidString
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNoPiaObjectCreationExpression(Me)
End Function
Public Function Update(guidString As string, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundNoPiaObjectCreationExpression
If guidString IsNot Me.GuidString OrElse initializerOpt IsNot Me.InitializerOpt OrElse type IsNot Me.Type Then
Dim result = New BoundNoPiaObjectCreationExpression(Me.Syntax, guidString, initializerOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAnonymousTypeCreationExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binderOpt As Binder.AnonymousTypeCreationBinder, declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AnonymousTypeCreationExpression, syntax, type, hasErrors OrElse declarations.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors())
Debug.Assert(Not (declarations.IsDefault), "Field 'declarations' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._BinderOpt = binderOpt
Me._Declarations = declarations
Me._Arguments = arguments
End Sub
Private ReadOnly _BinderOpt As Binder.AnonymousTypeCreationBinder
Public ReadOnly Property BinderOpt As Binder.AnonymousTypeCreationBinder
Get
Return _BinderOpt
End Get
End Property
Private ReadOnly _Declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess)
Public ReadOnly Property Declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess)
Get
Return _Declarations
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAnonymousTypeCreationExpression(Me)
End Function
Public Function Update(binderOpt As Binder.AnonymousTypeCreationBinder, declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess), arguments As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundAnonymousTypeCreationExpression
If binderOpt IsNot Me.BinderOpt OrElse declarations <> Me.Declarations OrElse arguments <> Me.Arguments OrElse type IsNot Me.Type Then
Dim result = New BoundAnonymousTypeCreationExpression(Me.Syntax, binderOpt, declarations, arguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAnonymousTypePropertyAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder.AnonymousTypeCreationBinder, propertyIndex As Integer, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.AnonymousTypePropertyAccess, syntax, type, hasErrors)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._PropertyIndex = propertyIndex
End Sub
Public Sub New(syntax As SyntaxNode, binder As Binder.AnonymousTypeCreationBinder, propertyIndex As Integer, type As TypeSymbol)
MyBase.New(BoundKind.AnonymousTypePropertyAccess, syntax, type)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._PropertyIndex = propertyIndex
End Sub
Private ReadOnly _Binder As Binder.AnonymousTypeCreationBinder
Public ReadOnly Property Binder As Binder.AnonymousTypeCreationBinder
Get
Return _Binder
End Get
End Property
Private ReadOnly _PropertyIndex As Integer
Public ReadOnly Property PropertyIndex As Integer
Get
Return _PropertyIndex
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAnonymousTypePropertyAccess(Me)
End Function
Public Function Update(binder As Binder.AnonymousTypeCreationBinder, propertyIndex As Integer, type As TypeSymbol) As BoundAnonymousTypePropertyAccess
If binder IsNot Me.Binder OrElse propertyIndex <> Me.PropertyIndex OrElse type IsNot Me.Type Then
Dim result = New BoundAnonymousTypePropertyAccess(Me.Syntax, binder, propertyIndex, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAnonymousTypeFieldInitializer
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder.AnonymousTypeFieldInitializerBinder, value As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AnonymousTypeFieldInitializer, syntax, type, hasErrors OrElse value.NonNullAndHasErrors())
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Value = value
End Sub
Private ReadOnly _Binder As Binder.AnonymousTypeFieldInitializerBinder
Public ReadOnly Property Binder As Binder.AnonymousTypeFieldInitializerBinder
Get
Return _Binder
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAnonymousTypeFieldInitializer(Me)
End Function
Public Function Update(binder As Binder.AnonymousTypeFieldInitializerBinder, value As BoundExpression, type As TypeSymbol) As BoundAnonymousTypeFieldInitializer
If binder IsNot Me.Binder OrElse value IsNot Me.Value OrElse type IsNot Me.Type Then
Dim result = New BoundAnonymousTypeFieldInitializer(Me.Syntax, binder, value, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundObjectInitializerExpressionBase
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PlaceholderOpt = placeholderOpt
Me._Initializers = initializers
End Sub
Private ReadOnly _PlaceholderOpt As BoundWithLValueExpressionPlaceholder
Public ReadOnly Property PlaceholderOpt As BoundWithLValueExpressionPlaceholder
Get
Return _PlaceholderOpt
End Get
End Property
Private ReadOnly _Initializers As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Initializers As ImmutableArray(Of BoundExpression)
Get
Return _Initializers
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundObjectInitializerExpression
Inherits BoundObjectInitializerExpressionBase
Public Sub New(syntax As SyntaxNode, createTemporaryLocalForInitialization As Boolean, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ObjectInitializerExpression, syntax, placeholderOpt, initializers, type, hasErrors OrElse placeholderOpt.NonNullAndHasErrors() OrElse initializers.NonNullAndHasErrors())
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CreateTemporaryLocalForInitialization = createTemporaryLocalForInitialization
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _CreateTemporaryLocalForInitialization As Boolean
Public ReadOnly Property CreateTemporaryLocalForInitialization As Boolean
Get
Return _CreateTemporaryLocalForInitialization
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitObjectInitializerExpression(Me)
End Function
Public Function Update(createTemporaryLocalForInitialization As Boolean, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundObjectInitializerExpression
If createTemporaryLocalForInitialization <> Me.CreateTemporaryLocalForInitialization OrElse placeholderOpt IsNot Me.PlaceholderOpt OrElse initializers <> Me.Initializers OrElse type IsNot Me.Type Then
Dim result = New BoundObjectInitializerExpression(Me.Syntax, createTemporaryLocalForInitialization, placeholderOpt, initializers, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCollectionInitializerExpression
Inherits BoundObjectInitializerExpressionBase
Public Sub New(syntax As SyntaxNode, placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CollectionInitializerExpression, syntax, placeholderOpt, initializers, type, hasErrors OrElse placeholderOpt.NonNullAndHasErrors() OrElse initializers.NonNullAndHasErrors())
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCollectionInitializerExpression(Me)
End Function
Public Function Update(placeholderOpt As BoundWithLValueExpressionPlaceholder, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundCollectionInitializerExpression
If placeholderOpt IsNot Me.PlaceholderOpt OrElse initializers <> Me.Initializers OrElse type IsNot Me.Type Then
Dim result = New BoundCollectionInitializerExpression(Me.Syntax, placeholderOpt, initializers, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNewT
Inherits BoundObjectCreationExpressionBase
Public Sub New(syntax As SyntaxNode, initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NewT, syntax, initializerOpt, type, hasErrors OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNewT(Me)
End Function
Public Function Update(initializerOpt As BoundObjectInitializerExpressionBase, type As TypeSymbol) As BoundNewT
If initializerOpt IsNot Me.InitializerOpt OrElse type IsNot Me.Type Then
Dim result = New BoundNewT(Me.Syntax, initializerOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDelegateCreationExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOpt As BoundExpression, method As MethodSymbol, relaxationLambdaOpt As BoundLambda, relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder, methodGroupOpt As BoundMethodGroup, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DelegateCreationExpression, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors() OrElse relaxationLambdaOpt.NonNullAndHasErrors() OrElse relaxationReceiverPlaceholderOpt.NonNullAndHasErrors() OrElse methodGroupOpt.NonNullAndHasErrors())
Debug.Assert(method IsNot Nothing, "Field 'method' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOpt = receiverOpt
Me._Method = method
Me._RelaxationLambdaOpt = relaxationLambdaOpt
Me._RelaxationReceiverPlaceholderOpt = relaxationReceiverPlaceholderOpt
Me._MethodGroupOpt = methodGroupOpt
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _Method As MethodSymbol
Public ReadOnly Property Method As MethodSymbol
Get
Return _Method
End Get
End Property
Private ReadOnly _RelaxationLambdaOpt As BoundLambda
Public ReadOnly Property RelaxationLambdaOpt As BoundLambda
Get
Return _RelaxationLambdaOpt
End Get
End Property
Private ReadOnly _RelaxationReceiverPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property RelaxationReceiverPlaceholderOpt As BoundRValuePlaceholder
Get
Return _RelaxationReceiverPlaceholderOpt
End Get
End Property
Private ReadOnly _MethodGroupOpt As BoundMethodGroup
Public ReadOnly Property MethodGroupOpt As BoundMethodGroup
Get
Return _MethodGroupOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDelegateCreationExpression(Me)
End Function
Public Function Update(receiverOpt As BoundExpression, method As MethodSymbol, relaxationLambdaOpt As BoundLambda, relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder, methodGroupOpt As BoundMethodGroup, type As TypeSymbol) As BoundDelegateCreationExpression
If receiverOpt IsNot Me.ReceiverOpt OrElse method IsNot Me.Method OrElse relaxationLambdaOpt IsNot Me.RelaxationLambdaOpt OrElse relaxationReceiverPlaceholderOpt IsNot Me.RelaxationReceiverPlaceholderOpt OrElse methodGroupOpt IsNot Me.MethodGroupOpt OrElse type IsNot Me.Type Then
Dim result = New BoundDelegateCreationExpression(Me.Syntax, receiverOpt, method, relaxationLambdaOpt, relaxationReceiverPlaceholderOpt, methodGroupOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayCreation
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, isParamArrayArgument As Boolean, bounds As ImmutableArray(Of BoundExpression), initializerOpt As BoundArrayInitialization, arrayLiteralOpt As BoundArrayLiteral, arrayLiteralConversion As ConversionKind, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayCreation, syntax, type, hasErrors OrElse bounds.NonNullAndHasErrors() OrElse initializerOpt.NonNullAndHasErrors() OrElse arrayLiteralOpt.NonNullAndHasErrors())
Debug.Assert(Not (bounds.IsDefault), "Field 'bounds' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsParamArrayArgument = isParamArrayArgument
Me._Bounds = bounds
Me._InitializerOpt = initializerOpt
Me._ArrayLiteralOpt = arrayLiteralOpt
Me._ArrayLiteralConversion = arrayLiteralConversion
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _IsParamArrayArgument As Boolean
Public ReadOnly Property IsParamArrayArgument As Boolean
Get
Return _IsParamArrayArgument
End Get
End Property
Private ReadOnly _Bounds As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Bounds As ImmutableArray(Of BoundExpression)
Get
Return _Bounds
End Get
End Property
Private ReadOnly _InitializerOpt As BoundArrayInitialization
Public ReadOnly Property InitializerOpt As BoundArrayInitialization
Get
Return _InitializerOpt
End Get
End Property
Private ReadOnly _ArrayLiteralOpt As BoundArrayLiteral
Public ReadOnly Property ArrayLiteralOpt As BoundArrayLiteral
Get
Return _ArrayLiteralOpt
End Get
End Property
Private ReadOnly _ArrayLiteralConversion As ConversionKind
Public ReadOnly Property ArrayLiteralConversion As ConversionKind
Get
Return _ArrayLiteralConversion
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayCreation(Me)
End Function
Public Function Update(isParamArrayArgument As Boolean, bounds As ImmutableArray(Of BoundExpression), initializerOpt As BoundArrayInitialization, arrayLiteralOpt As BoundArrayLiteral, arrayLiteralConversion As ConversionKind, type As TypeSymbol) As BoundArrayCreation
If isParamArrayArgument <> Me.IsParamArrayArgument OrElse bounds <> Me.Bounds OrElse initializerOpt IsNot Me.InitializerOpt OrElse arrayLiteralOpt IsNot Me.ArrayLiteralOpt OrElse arrayLiteralConversion <> Me.ArrayLiteralConversion OrElse type IsNot Me.Type Then
Dim result = New BoundArrayCreation(Me.Syntax, isParamArrayArgument, bounds, initializerOpt, arrayLiteralOpt, arrayLiteralConversion, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayLiteral
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, hasDominantType As Boolean, numberOfCandidates As Integer, inferredType As ArrayTypeSymbol, bounds As ImmutableArray(Of BoundExpression), initializer As BoundArrayInitialization, binder As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayLiteral, syntax, Nothing, hasErrors OrElse bounds.NonNullAndHasErrors() OrElse initializer.NonNullAndHasErrors())
Debug.Assert(inferredType IsNot Nothing, "Field 'inferredType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (bounds.IsDefault), "Field 'bounds' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initializer IsNot Nothing, "Field 'initializer' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._HasDominantType = hasDominantType
Me._NumberOfCandidates = numberOfCandidates
Me._InferredType = inferredType
Me._Bounds = bounds
Me._Initializer = initializer
Me._Binder = binder
End Sub
Private ReadOnly _HasDominantType As Boolean
Public ReadOnly Property HasDominantType As Boolean
Get
Return _HasDominantType
End Get
End Property
Private ReadOnly _NumberOfCandidates As Integer
Public ReadOnly Property NumberOfCandidates As Integer
Get
Return _NumberOfCandidates
End Get
End Property
Private ReadOnly _InferredType As ArrayTypeSymbol
Public ReadOnly Property InferredType As ArrayTypeSymbol
Get
Return _InferredType
End Get
End Property
Private ReadOnly _Bounds As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Bounds As ImmutableArray(Of BoundExpression)
Get
Return _Bounds
End Get
End Property
Private ReadOnly _Initializer As BoundArrayInitialization
Public ReadOnly Property Initializer As BoundArrayInitialization
Get
Return _Initializer
End Get
End Property
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayLiteral(Me)
End Function
Public Function Update(hasDominantType As Boolean, numberOfCandidates As Integer, inferredType As ArrayTypeSymbol, bounds As ImmutableArray(Of BoundExpression), initializer As BoundArrayInitialization, binder As Binder) As BoundArrayLiteral
If hasDominantType <> Me.HasDominantType OrElse numberOfCandidates <> Me.NumberOfCandidates OrElse inferredType IsNot Me.InferredType OrElse bounds <> Me.Bounds OrElse initializer IsNot Me.Initializer OrElse binder IsNot Me.Binder Then
Dim result = New BoundArrayLiteral(Me.Syntax, hasDominantType, numberOfCandidates, inferredType, bounds, initializer, binder, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundArrayInitialization
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ArrayInitialization, syntax, type, hasErrors OrElse initializers.NonNullAndHasErrors())
Debug.Assert(Not (initializers.IsDefault), "Field 'initializers' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Initializers = initializers
End Sub
Private ReadOnly _Initializers As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Initializers As ImmutableArray(Of BoundExpression)
Get
Return _Initializers
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitArrayInitialization(Me)
End Function
Public Function Update(initializers As ImmutableArray(Of BoundExpression), type As TypeSymbol) As BoundArrayInitialization
If initializers <> Me.Initializers OrElse type IsNot Me.Type Then
Dim result = New BoundArrayInitialization(Me.Syntax, initializers, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundFieldAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOpt As BoundExpression, fieldSymbol As FieldSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, constantsInProgressOpt As ConstantFieldsInProgress, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.FieldAccess, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(fieldSymbol IsNot Nothing, "Field 'fieldSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOpt = receiverOpt
Me._FieldSymbol = fieldSymbol
Me._IsLValue = isLValue
Me._SuppressVirtualCalls = suppressVirtualCalls
Me._ConstantsInProgressOpt = constantsInProgressOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _FieldSymbol As FieldSymbol
Public ReadOnly Property FieldSymbol As FieldSymbol
Get
Return _FieldSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _SuppressVirtualCalls As Boolean
Public Overrides ReadOnly Property SuppressVirtualCalls As Boolean
Get
Return _SuppressVirtualCalls
End Get
End Property
Private ReadOnly _ConstantsInProgressOpt As ConstantFieldsInProgress
Public ReadOnly Property ConstantsInProgressOpt As ConstantFieldsInProgress
Get
Return _ConstantsInProgressOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitFieldAccess(Me)
End Function
Public Function Update(receiverOpt As BoundExpression, fieldSymbol As FieldSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, constantsInProgressOpt As ConstantFieldsInProgress, type As TypeSymbol) As BoundFieldAccess
If receiverOpt IsNot Me.ReceiverOpt OrElse fieldSymbol IsNot Me.FieldSymbol OrElse isLValue <> Me.IsLValue OrElse suppressVirtualCalls <> Me.SuppressVirtualCalls OrElse constantsInProgressOpt IsNot Me.ConstantsInProgressOpt OrElse type IsNot Me.Type Then
Dim result = New BoundFieldAccess(Me.Syntax, receiverOpt, fieldSymbol, isLValue, suppressVirtualCalls, constantsInProgressOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPropertyAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, propertySymbol As PropertySymbol, propertyGroupOpt As BoundPropertyGroup, accessKind As PropertyAccessKind, isWriteable As Boolean, isLValue As Boolean, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.PropertyAccess, syntax, type, hasErrors OrElse propertyGroupOpt.NonNullAndHasErrors() OrElse receiverOpt.NonNullAndHasErrors() OrElse arguments.NonNullAndHasErrors())
Debug.Assert(propertySymbol IsNot Nothing, "Field 'propertySymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (arguments.IsDefault), "Field 'arguments' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PropertySymbol = propertySymbol
Me._PropertyGroupOpt = propertyGroupOpt
Me._AccessKind = accessKind
Me._IsWriteable = isWriteable
Me._IsLValue = isLValue
Me._ReceiverOpt = receiverOpt
Me._Arguments = arguments
Me._DefaultArguments = defaultArguments
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _PropertySymbol As PropertySymbol
Public ReadOnly Property PropertySymbol As PropertySymbol
Get
Return _PropertySymbol
End Get
End Property
Private ReadOnly _PropertyGroupOpt As BoundPropertyGroup
Public ReadOnly Property PropertyGroupOpt As BoundPropertyGroup
Get
Return _PropertyGroupOpt
End Get
End Property
Private ReadOnly _AccessKind As PropertyAccessKind
Public ReadOnly Property AccessKind As PropertyAccessKind
Get
Return _AccessKind
End Get
End Property
Private ReadOnly _IsWriteable As Boolean
Public ReadOnly Property IsWriteable As Boolean
Get
Return _IsWriteable
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly Property Arguments As ImmutableArray(Of BoundExpression)
Get
Return _Arguments
End Get
End Property
Private ReadOnly _DefaultArguments As BitVector
Public ReadOnly Property DefaultArguments As BitVector
Get
Return _DefaultArguments
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPropertyAccess(Me)
End Function
Public Function Update(propertySymbol As PropertySymbol, propertyGroupOpt As BoundPropertyGroup, accessKind As PropertyAccessKind, isWriteable As Boolean, isLValue As Boolean, receiverOpt As BoundExpression, arguments As ImmutableArray(Of BoundExpression), defaultArguments As BitVector, type As TypeSymbol) As BoundPropertyAccess
If propertySymbol IsNot Me.PropertySymbol OrElse propertyGroupOpt IsNot Me.PropertyGroupOpt OrElse accessKind <> Me.AccessKind OrElse isWriteable <> Me.IsWriteable OrElse isLValue <> Me.IsLValue OrElse receiverOpt IsNot Me.ReceiverOpt OrElse arguments <> Me.Arguments OrElse defaultArguments <> Me.DefaultArguments OrElse type IsNot Me.Type Then
Dim result = New BoundPropertyAccess(Me.Syntax, propertySymbol, propertyGroupOpt, accessKind, isWriteable, isLValue, receiverOpt, arguments, defaultArguments, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundEventAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOpt As BoundExpression, eventSymbol As EventSymbol, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.EventAccess, syntax, type, hasErrors OrElse receiverOpt.NonNullAndHasErrors())
Debug.Assert(eventSymbol IsNot Nothing, "Field 'eventSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOpt = receiverOpt
Me._EventSymbol = eventSymbol
End Sub
Private ReadOnly _ReceiverOpt As BoundExpression
Public ReadOnly Property ReceiverOpt As BoundExpression
Get
Return _ReceiverOpt
End Get
End Property
Private ReadOnly _EventSymbol As EventSymbol
Public ReadOnly Property EventSymbol As EventSymbol
Get
Return _EventSymbol
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitEventAccess(Me)
End Function
Public Function Update(receiverOpt As BoundExpression, eventSymbol As EventSymbol, type As TypeSymbol) As BoundEventAccess
If receiverOpt IsNot Me.ReceiverOpt OrElse eventSymbol IsNot Me.EventSymbol OrElse type IsNot Me.Type Then
Dim result = New BoundEventAccess(Me.Syntax, receiverOpt, eventSymbol, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundBlock
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statementListSyntax As SyntaxList(Of StatementSyntax), locals As ImmutableArray(Of LocalSymbol), statements As ImmutableArray(Of BoundStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Block, syntax, hasErrors OrElse statements.NonNullAndHasErrors())
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (statements.IsDefault), "Field 'statements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._StatementListSyntax = statementListSyntax
Me._Locals = locals
Me._Statements = statements
End Sub
Private ReadOnly _StatementListSyntax As SyntaxList(Of StatementSyntax)
Public ReadOnly Property StatementListSyntax As SyntaxList(Of StatementSyntax)
Get
Return _StatementListSyntax
End Get
End Property
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
Private ReadOnly _Statements As ImmutableArray(Of BoundStatement)
Public ReadOnly Property Statements As ImmutableArray(Of BoundStatement)
Get
Return _Statements
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitBlock(Me)
End Function
Public Function Update(statementListSyntax As SyntaxList(Of StatementSyntax), locals As ImmutableArray(Of LocalSymbol), statements As ImmutableArray(Of BoundStatement)) As BoundBlock
If statementListSyntax <> Me.StatementListSyntax OrElse locals <> Me.Locals OrElse statements <> Me.Statements Then
Dim result = New BoundBlock(Me.Syntax, statementListSyntax, locals, statements, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundStateMachineScope
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, fields As ImmutableArray(Of FieldSymbol), statement As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.StateMachineScope, syntax, hasErrors OrElse statement.NonNullAndHasErrors())
Debug.Assert(Not (fields.IsDefault), "Field 'fields' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(statement IsNot Nothing, "Field 'statement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Fields = fields
Me._Statement = statement
End Sub
Private ReadOnly _Fields As ImmutableArray(Of FieldSymbol)
Public ReadOnly Property Fields As ImmutableArray(Of FieldSymbol)
Get
Return _Fields
End Get
End Property
Private ReadOnly _Statement As BoundStatement
Public ReadOnly Property Statement As BoundStatement
Get
Return _Statement
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitStateMachineScope(Me)
End Function
Public Function Update(fields As ImmutableArray(Of FieldSymbol), statement As BoundStatement) As BoundStateMachineScope
If fields <> Me.Fields OrElse statement IsNot Me.Statement Then
Dim result = New BoundStateMachineScope(Me.Syntax, fields, statement, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundLocalDeclarationBase
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend NotInheritable Class BoundLocalDeclaration
Inherits BoundLocalDeclarationBase
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, declarationInitializerOpt As BoundExpression, identifierInitializerOpt As BoundArrayCreation, initializedByAsNew As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LocalDeclaration, syntax, hasErrors OrElse declarationInitializerOpt.NonNullAndHasErrors() OrElse identifierInitializerOpt.NonNullAndHasErrors())
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._DeclarationInitializerOpt = declarationInitializerOpt
Me._IdentifierInitializerOpt = identifierInitializerOpt
Me._InitializedByAsNew = initializedByAsNew
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LocalSymbol As LocalSymbol
Public ReadOnly Property LocalSymbol As LocalSymbol
Get
Return _LocalSymbol
End Get
End Property
Private ReadOnly _DeclarationInitializerOpt As BoundExpression
Public ReadOnly Property DeclarationInitializerOpt As BoundExpression
Get
Return _DeclarationInitializerOpt
End Get
End Property
Private ReadOnly _IdentifierInitializerOpt As BoundArrayCreation
Public ReadOnly Property IdentifierInitializerOpt As BoundArrayCreation
Get
Return _IdentifierInitializerOpt
End Get
End Property
Private ReadOnly _InitializedByAsNew As Boolean
Public ReadOnly Property InitializedByAsNew As Boolean
Get
Return _InitializedByAsNew
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLocalDeclaration(Me)
End Function
Public Function Update(localSymbol As LocalSymbol, declarationInitializerOpt As BoundExpression, identifierInitializerOpt As BoundArrayCreation, initializedByAsNew As Boolean) As BoundLocalDeclaration
If localSymbol IsNot Me.LocalSymbol OrElse declarationInitializerOpt IsNot Me.DeclarationInitializerOpt OrElse identifierInitializerOpt IsNot Me.IdentifierInitializerOpt OrElse initializedByAsNew <> Me.InitializedByAsNew Then
Dim result = New BoundLocalDeclaration(Me.Syntax, localSymbol, declarationInitializerOpt, identifierInitializerOpt, initializedByAsNew, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAsNewLocalDeclarations
Inherits BoundLocalDeclarationBase
Public Sub New(syntax As SyntaxNode, localDeclarations As ImmutableArray(Of BoundLocalDeclaration), initializer As BoundExpression, binder As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AsNewLocalDeclarations, syntax, hasErrors OrElse localDeclarations.NonNullAndHasErrors() OrElse initializer.NonNullAndHasErrors())
Debug.Assert(Not (localDeclarations.IsDefault), "Field 'localDeclarations' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initializer IsNot Nothing, "Field 'initializer' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalDeclarations = localDeclarations
Me._Initializer = initializer
Me._Binder = binder
End Sub
Private ReadOnly _LocalDeclarations As ImmutableArray(Of BoundLocalDeclaration)
Public ReadOnly Property LocalDeclarations As ImmutableArray(Of BoundLocalDeclaration)
Get
Return _LocalDeclarations
End Get
End Property
Private ReadOnly _Initializer As BoundExpression
Public ReadOnly Property Initializer As BoundExpression
Get
Return _Initializer
End Get
End Property
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAsNewLocalDeclarations(Me)
End Function
Public Function Update(localDeclarations As ImmutableArray(Of BoundLocalDeclaration), initializer As BoundExpression, binder As Binder) As BoundAsNewLocalDeclarations
If localDeclarations <> Me.LocalDeclarations OrElse initializer IsNot Me.Initializer OrElse binder IsNot Me.Binder Then
Dim result = New BoundAsNewLocalDeclarations(Me.Syntax, localDeclarations, initializer, binder, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundDimStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, localDeclarations As ImmutableArray(Of BoundLocalDeclarationBase), initializerOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DimStatement, syntax, hasErrors OrElse localDeclarations.NonNullAndHasErrors() OrElse initializerOpt.NonNullAndHasErrors())
Debug.Assert(Not (localDeclarations.IsDefault), "Field 'localDeclarations' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalDeclarations = localDeclarations
Me._InitializerOpt = initializerOpt
End Sub
Private ReadOnly _LocalDeclarations As ImmutableArray(Of BoundLocalDeclarationBase)
Public ReadOnly Property LocalDeclarations As ImmutableArray(Of BoundLocalDeclarationBase)
Get
Return _LocalDeclarations
End Get
End Property
Private ReadOnly _InitializerOpt As BoundExpression
Public ReadOnly Property InitializerOpt As BoundExpression
Get
Return _InitializerOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDimStatement(Me)
End Function
Public Function Update(localDeclarations As ImmutableArray(Of BoundLocalDeclarationBase), initializerOpt As BoundExpression) As BoundDimStatement
If localDeclarations <> Me.LocalDeclarations OrElse initializerOpt IsNot Me.InitializerOpt Then
Dim result = New BoundDimStatement(Me.Syntax, localDeclarations, initializerOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend Class BoundInitializer
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyBase.New(BoundKind.Initializer, syntax, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode)
MyBase.New(BoundKind.Initializer, syntax)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInitializer(Me)
End Function
End Class
Partial Friend MustInherit Class BoundFieldOrPropertyInitializer
Inherits BoundInitializer
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, hasErrors)
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._MemberAccessExpressionOpt = memberAccessExpressionOpt
Me._InitialValue = initialValue
Me._BinderOpt = binderOpt
End Sub
Private ReadOnly _MemberAccessExpressionOpt As BoundExpression
Public ReadOnly Property MemberAccessExpressionOpt As BoundExpression
Get
Return _MemberAccessExpressionOpt
End Get
End Property
Private ReadOnly _InitialValue As BoundExpression
Public ReadOnly Property InitialValue As BoundExpression
Get
Return _InitialValue
End Get
End Property
Private ReadOnly _BinderOpt As Binder
Public ReadOnly Property BinderOpt As Binder
Get
Return _BinderOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundFieldInitializer
Inherits BoundFieldOrPropertyInitializer
Public Sub New(syntax As SyntaxNode, initializedFields As ImmutableArray(Of FieldSymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.FieldInitializer, syntax, memberAccessExpressionOpt, initialValue, binderOpt, hasErrors OrElse memberAccessExpressionOpt.NonNullAndHasErrors() OrElse initialValue.NonNullAndHasErrors())
Debug.Assert(Not (initializedFields.IsDefault), "Field 'initializedFields' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitializedFields = initializedFields
End Sub
Private ReadOnly _InitializedFields As ImmutableArray(Of FieldSymbol)
Public ReadOnly Property InitializedFields As ImmutableArray(Of FieldSymbol)
Get
Return _InitializedFields
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitFieldInitializer(Me)
End Function
Public Function Update(initializedFields As ImmutableArray(Of FieldSymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder) As BoundFieldInitializer
If initializedFields <> Me.InitializedFields OrElse memberAccessExpressionOpt IsNot Me.MemberAccessExpressionOpt OrElse initialValue IsNot Me.InitialValue OrElse binderOpt IsNot Me.BinderOpt Then
Dim result = New BoundFieldInitializer(Me.Syntax, initializedFields, memberAccessExpressionOpt, initialValue, binderOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPropertyInitializer
Inherits BoundFieldOrPropertyInitializer
Public Sub New(syntax As SyntaxNode, initializedProperties As ImmutableArray(Of PropertySymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.PropertyInitializer, syntax, memberAccessExpressionOpt, initialValue, binderOpt, hasErrors OrElse memberAccessExpressionOpt.NonNullAndHasErrors() OrElse initialValue.NonNullAndHasErrors())
Debug.Assert(Not (initializedProperties.IsDefault), "Field 'initializedProperties' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitializedProperties = initializedProperties
End Sub
Private ReadOnly _InitializedProperties As ImmutableArray(Of PropertySymbol)
Public ReadOnly Property InitializedProperties As ImmutableArray(Of PropertySymbol)
Get
Return _InitializedProperties
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPropertyInitializer(Me)
End Function
Public Function Update(initializedProperties As ImmutableArray(Of PropertySymbol), memberAccessExpressionOpt As BoundExpression, initialValue As BoundExpression, binderOpt As Binder) As BoundPropertyInitializer
If initializedProperties <> Me.InitializedProperties OrElse memberAccessExpressionOpt IsNot Me.MemberAccessExpressionOpt OrElse initialValue IsNot Me.InitialValue OrElse binderOpt IsNot Me.BinderOpt Then
Dim result = New BoundPropertyInitializer(Me.Syntax, initializedProperties, memberAccessExpressionOpt, initialValue, binderOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundParameterEqualsValue
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, parameter As ParameterSymbol, value As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ParameterEqualsValue, syntax, hasErrors OrElse value.NonNullAndHasErrors())
Debug.Assert(parameter IsNot Nothing, "Field 'parameter' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Parameter = parameter
Me._Value = value
End Sub
Private ReadOnly _Parameter As ParameterSymbol
Public ReadOnly Property Parameter As ParameterSymbol
Get
Return _Parameter
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitParameterEqualsValue(Me)
End Function
Public Function Update(parameter As ParameterSymbol, value As BoundExpression) As BoundParameterEqualsValue
If parameter IsNot Me.Parameter OrElse value IsNot Me.Value Then
Dim result = New BoundParameterEqualsValue(Me.Syntax, parameter, value, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGlobalStatementInitializer
Inherits BoundInitializer
Public Sub New(syntax As SyntaxNode, statement As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GlobalStatementInitializer, syntax, hasErrors OrElse statement.NonNullAndHasErrors())
Debug.Assert(statement IsNot Nothing, "Field 'statement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Statement = statement
End Sub
Private ReadOnly _Statement As BoundStatement
Public ReadOnly Property Statement As BoundStatement
Get
Return _Statement
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGlobalStatementInitializer(Me)
End Function
Public Function Update(statement As BoundStatement) As BoundGlobalStatementInitializer
If statement IsNot Me.Statement Then
Dim result = New BoundGlobalStatementInitializer(Me.Syntax, statement, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSequence
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, locals As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression), valueOpt As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Sequence, syntax, type, hasErrors OrElse sideEffects.NonNullAndHasErrors() OrElse valueOpt.NonNullAndHasErrors())
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (sideEffects.IsDefault), "Field 'sideEffects' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Locals = locals
Me._SideEffects = sideEffects
Me._ValueOpt = valueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
Private ReadOnly _SideEffects As ImmutableArray(Of BoundExpression)
Public ReadOnly Property SideEffects As ImmutableArray(Of BoundExpression)
Get
Return _SideEffects
End Get
End Property
Private ReadOnly _ValueOpt As BoundExpression
Public ReadOnly Property ValueOpt As BoundExpression
Get
Return _ValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSequence(Me)
End Function
Public Function Update(locals As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression), valueOpt As BoundExpression, type As TypeSymbol) As BoundSequence
If locals <> Me.Locals OrElse sideEffects <> Me.SideEffects OrElse valueOpt IsNot Me.ValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundSequence(Me.Syntax, locals, sideEffects, valueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundExpressionStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ExpressionStatement, syntax, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitExpressionStatement(Me)
End Function
Public Function Update(expression As BoundExpression) As BoundExpressionStatement
If expression IsNot Me.Expression Then
Dim result = New BoundExpressionStatement(Me.Syntax, expression, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundIfStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, consequence As BoundStatement, alternativeOpt As BoundStatement, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.IfStatement, syntax, hasErrors OrElse condition.NonNullAndHasErrors() OrElse consequence.NonNullAndHasErrors() OrElse alternativeOpt.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(consequence IsNot Nothing, "Field 'consequence' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._Consequence = consequence
Me._AlternativeOpt = alternativeOpt
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _Consequence As BoundStatement
Public ReadOnly Property Consequence As BoundStatement
Get
Return _Consequence
End Get
End Property
Private ReadOnly _AlternativeOpt As BoundStatement
Public ReadOnly Property AlternativeOpt As BoundStatement
Get
Return _AlternativeOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitIfStatement(Me)
End Function
Public Function Update(condition As BoundExpression, consequence As BoundStatement, alternativeOpt As BoundStatement) As BoundIfStatement
If condition IsNot Me.Condition OrElse consequence IsNot Me.Consequence OrElse alternativeOpt IsNot Me.AlternativeOpt Then
Dim result = New BoundIfStatement(Me.Syntax, condition, consequence, alternativeOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSelectStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, expressionStatement As BoundExpressionStatement, exprPlaceholderOpt As BoundRValuePlaceholder, caseBlocks As ImmutableArray(Of BoundCaseBlock), recommendSwitchTable As Boolean, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SelectStatement, syntax, hasErrors OrElse expressionStatement.NonNullAndHasErrors() OrElse exprPlaceholderOpt.NonNullAndHasErrors() OrElse caseBlocks.NonNullAndHasErrors())
Debug.Assert(expressionStatement IsNot Nothing, "Field 'expressionStatement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (caseBlocks.IsDefault), "Field 'caseBlocks' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ExpressionStatement = expressionStatement
Me._ExprPlaceholderOpt = exprPlaceholderOpt
Me._CaseBlocks = caseBlocks
Me._RecommendSwitchTable = recommendSwitchTable
Me._ExitLabel = exitLabel
End Sub
Private ReadOnly _ExpressionStatement As BoundExpressionStatement
Public ReadOnly Property ExpressionStatement As BoundExpressionStatement
Get
Return _ExpressionStatement
End Get
End Property
Private ReadOnly _ExprPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property ExprPlaceholderOpt As BoundRValuePlaceholder
Get
Return _ExprPlaceholderOpt
End Get
End Property
Private ReadOnly _CaseBlocks As ImmutableArray(Of BoundCaseBlock)
Public ReadOnly Property CaseBlocks As ImmutableArray(Of BoundCaseBlock)
Get
Return _CaseBlocks
End Get
End Property
Private ReadOnly _RecommendSwitchTable As Boolean
Public ReadOnly Property RecommendSwitchTable As Boolean
Get
Return _RecommendSwitchTable
End Get
End Property
Private ReadOnly _ExitLabel As LabelSymbol
Public ReadOnly Property ExitLabel As LabelSymbol
Get
Return _ExitLabel
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSelectStatement(Me)
End Function
Public Function Update(expressionStatement As BoundExpressionStatement, exprPlaceholderOpt As BoundRValuePlaceholder, caseBlocks As ImmutableArray(Of BoundCaseBlock), recommendSwitchTable As Boolean, exitLabel As LabelSymbol) As BoundSelectStatement
If expressionStatement IsNot Me.ExpressionStatement OrElse exprPlaceholderOpt IsNot Me.ExprPlaceholderOpt OrElse caseBlocks <> Me.CaseBlocks OrElse recommendSwitchTable <> Me.RecommendSwitchTable OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundSelectStatement(Me.Syntax, expressionStatement, exprPlaceholderOpt, caseBlocks, recommendSwitchTable, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCaseBlock
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, caseStatement As BoundCaseStatement, body As BoundBlock, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CaseBlock, syntax, hasErrors OrElse caseStatement.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(caseStatement IsNot Nothing, "Field 'caseStatement' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CaseStatement = caseStatement
Me._Body = body
End Sub
Private ReadOnly _CaseStatement As BoundCaseStatement
Public ReadOnly Property CaseStatement As BoundCaseStatement
Get
Return _CaseStatement
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCaseBlock(Me)
End Function
Public Function Update(caseStatement As BoundCaseStatement, body As BoundBlock) As BoundCaseBlock
If caseStatement IsNot Me.CaseStatement OrElse body IsNot Me.Body Then
Dim result = New BoundCaseBlock(Me.Syntax, caseStatement, body, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCaseStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, caseClauses As ImmutableArray(Of BoundCaseClause), conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CaseStatement, syntax, hasErrors OrElse caseClauses.NonNullAndHasErrors() OrElse conditionOpt.NonNullAndHasErrors())
Debug.Assert(Not (caseClauses.IsDefault), "Field 'caseClauses' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CaseClauses = caseClauses
Me._ConditionOpt = conditionOpt
End Sub
Private ReadOnly _CaseClauses As ImmutableArray(Of BoundCaseClause)
Public ReadOnly Property CaseClauses As ImmutableArray(Of BoundCaseClause)
Get
Return _CaseClauses
End Get
End Property
Private ReadOnly _ConditionOpt As BoundExpression
Public ReadOnly Property ConditionOpt As BoundExpression
Get
Return _ConditionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCaseStatement(Me)
End Function
Public Function Update(caseClauses As ImmutableArray(Of BoundCaseClause), conditionOpt As BoundExpression) As BoundCaseStatement
If caseClauses <> Me.CaseClauses OrElse conditionOpt IsNot Me.ConditionOpt Then
Dim result = New BoundCaseStatement(Me.Syntax, caseClauses, conditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundCaseClause
Inherits BoundNode
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode)
MyBase.New(kind, syntax)
End Sub
End Class
Partial Friend MustInherit Class BoundSingleValueCaseClause
Inherits BoundCaseClause
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, valueOpt As BoundExpression, conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, hasErrors)
Me._ValueOpt = valueOpt
Me._ConditionOpt = conditionOpt
End Sub
Private ReadOnly _ValueOpt As BoundExpression
Public ReadOnly Property ValueOpt As BoundExpression
Get
Return _ValueOpt
End Get
End Property
Private ReadOnly _ConditionOpt As BoundExpression
Public ReadOnly Property ConditionOpt As BoundExpression
Get
Return _ConditionOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundSimpleCaseClause
Inherits BoundSingleValueCaseClause
Public Sub New(syntax As SyntaxNode, valueOpt As BoundExpression, conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SimpleCaseClause, syntax, valueOpt, conditionOpt, hasErrors OrElse valueOpt.NonNullAndHasErrors() OrElse conditionOpt.NonNullAndHasErrors())
Validate()
End Sub
Private Partial Sub Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSimpleCaseClause(Me)
End Function
Public Function Update(valueOpt As BoundExpression, conditionOpt As BoundExpression) As BoundSimpleCaseClause
If valueOpt IsNot Me.ValueOpt OrElse conditionOpt IsNot Me.ConditionOpt Then
Dim result = New BoundSimpleCaseClause(Me.Syntax, valueOpt, conditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRangeCaseClause
Inherits BoundCaseClause
Public Sub New(syntax As SyntaxNode, lowerBoundOpt As BoundExpression, upperBoundOpt As BoundExpression, lowerBoundConditionOpt As BoundExpression, upperBoundConditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RangeCaseClause, syntax, hasErrors OrElse lowerBoundOpt.NonNullAndHasErrors() OrElse upperBoundOpt.NonNullAndHasErrors() OrElse lowerBoundConditionOpt.NonNullAndHasErrors() OrElse upperBoundConditionOpt.NonNullAndHasErrors())
Me._LowerBoundOpt = lowerBoundOpt
Me._UpperBoundOpt = upperBoundOpt
Me._LowerBoundConditionOpt = lowerBoundConditionOpt
Me._UpperBoundConditionOpt = upperBoundConditionOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LowerBoundOpt As BoundExpression
Public ReadOnly Property LowerBoundOpt As BoundExpression
Get
Return _LowerBoundOpt
End Get
End Property
Private ReadOnly _UpperBoundOpt As BoundExpression
Public ReadOnly Property UpperBoundOpt As BoundExpression
Get
Return _UpperBoundOpt
End Get
End Property
Private ReadOnly _LowerBoundConditionOpt As BoundExpression
Public ReadOnly Property LowerBoundConditionOpt As BoundExpression
Get
Return _LowerBoundConditionOpt
End Get
End Property
Private ReadOnly _UpperBoundConditionOpt As BoundExpression
Public ReadOnly Property UpperBoundConditionOpt As BoundExpression
Get
Return _UpperBoundConditionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRangeCaseClause(Me)
End Function
Public Function Update(lowerBoundOpt As BoundExpression, upperBoundOpt As BoundExpression, lowerBoundConditionOpt As BoundExpression, upperBoundConditionOpt As BoundExpression) As BoundRangeCaseClause
If lowerBoundOpt IsNot Me.LowerBoundOpt OrElse upperBoundOpt IsNot Me.UpperBoundOpt OrElse lowerBoundConditionOpt IsNot Me.LowerBoundConditionOpt OrElse upperBoundConditionOpt IsNot Me.UpperBoundConditionOpt Then
Dim result = New BoundRangeCaseClause(Me.Syntax, lowerBoundOpt, upperBoundOpt, lowerBoundConditionOpt, upperBoundConditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRelationalCaseClause
Inherits BoundSingleValueCaseClause
Public Sub New(syntax As SyntaxNode, operatorKind As BinaryOperatorKind, valueOpt As BoundExpression, conditionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RelationalCaseClause, syntax, valueOpt, conditionOpt, hasErrors OrElse valueOpt.NonNullAndHasErrors() OrElse conditionOpt.NonNullAndHasErrors())
Me._OperatorKind = operatorKind
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OperatorKind As BinaryOperatorKind
Public ReadOnly Property OperatorKind As BinaryOperatorKind
Get
Return _OperatorKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRelationalCaseClause(Me)
End Function
Public Function Update(operatorKind As BinaryOperatorKind, valueOpt As BoundExpression, conditionOpt As BoundExpression) As BoundRelationalCaseClause
If operatorKind <> Me.OperatorKind OrElse valueOpt IsNot Me.ValueOpt OrElse conditionOpt IsNot Me.ConditionOpt Then
Dim result = New BoundRelationalCaseClause(Me.Syntax, operatorKind, valueOpt, conditionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundLoopStatement
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, continueLabel As LabelSymbol, exitLabel As LabelSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, hasErrors)
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ContinueLabel = continueLabel
Me._ExitLabel = exitLabel
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, continueLabel As LabelSymbol, exitLabel As LabelSymbol)
MyBase.New(kind, syntax)
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ContinueLabel = continueLabel
Me._ExitLabel = exitLabel
End Sub
Private ReadOnly _ContinueLabel As LabelSymbol
Public ReadOnly Property ContinueLabel As LabelSymbol
Get
Return _ContinueLabel
End Get
End Property
Private ReadOnly _ExitLabel As LabelSymbol
Public ReadOnly Property ExitLabel As LabelSymbol
Get
Return _ExitLabel
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundDoLoopStatement
Inherits BoundLoopStatement
Public Sub New(syntax As SyntaxNode, topConditionOpt As BoundExpression, bottomConditionOpt As BoundExpression, topConditionIsUntil As Boolean, bottomConditionIsUntil As Boolean, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.DoLoopStatement, syntax, continueLabel, exitLabel, hasErrors OrElse topConditionOpt.NonNullAndHasErrors() OrElse bottomConditionOpt.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TopConditionOpt = topConditionOpt
Me._BottomConditionOpt = bottomConditionOpt
Me._TopConditionIsUntil = topConditionIsUntil
Me._BottomConditionIsUntil = bottomConditionIsUntil
Me._Body = body
End Sub
Private ReadOnly _TopConditionOpt As BoundExpression
Public ReadOnly Property TopConditionOpt As BoundExpression
Get
Return _TopConditionOpt
End Get
End Property
Private ReadOnly _BottomConditionOpt As BoundExpression
Public ReadOnly Property BottomConditionOpt As BoundExpression
Get
Return _BottomConditionOpt
End Get
End Property
Private ReadOnly _TopConditionIsUntil As Boolean
Public ReadOnly Property TopConditionIsUntil As Boolean
Get
Return _TopConditionIsUntil
End Get
End Property
Private ReadOnly _BottomConditionIsUntil As Boolean
Public ReadOnly Property BottomConditionIsUntil As Boolean
Get
Return _BottomConditionIsUntil
End Get
End Property
Private ReadOnly _Body As BoundStatement
Public ReadOnly Property Body As BoundStatement
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitDoLoopStatement(Me)
End Function
Public Function Update(topConditionOpt As BoundExpression, bottomConditionOpt As BoundExpression, topConditionIsUntil As Boolean, bottomConditionIsUntil As Boolean, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundDoLoopStatement
If topConditionOpt IsNot Me.TopConditionOpt OrElse bottomConditionOpt IsNot Me.BottomConditionOpt OrElse topConditionIsUntil <> Me.TopConditionIsUntil OrElse bottomConditionIsUntil <> Me.BottomConditionIsUntil OrElse body IsNot Me.Body OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundDoLoopStatement(Me.Syntax, topConditionOpt, bottomConditionOpt, topConditionIsUntil, bottomConditionIsUntil, body, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundWhileStatement
Inherits BoundLoopStatement
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.WhileStatement, syntax, continueLabel, exitLabel, hasErrors OrElse condition.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._Body = body
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _Body As BoundStatement
Public ReadOnly Property Body As BoundStatement
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWhileStatement(Me)
End Function
Public Function Update(condition As BoundExpression, body As BoundStatement, continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundWhileStatement
If condition IsNot Me.Condition OrElse body IsNot Me.Body OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundWhileStatement(Me.Syntax, condition, body, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundForStatement
Inherits BoundLoopStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, continueLabel, exitLabel, hasErrors)
Debug.Assert(controlVariable IsNot Nothing, "Field 'controlVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._DeclaredOrInferredLocalOpt = declaredOrInferredLocalOpt
Me._ControlVariable = controlVariable
Me._Body = body
Me._NextVariablesOpt = nextVariablesOpt
End Sub
Private ReadOnly _DeclaredOrInferredLocalOpt As LocalSymbol
Public ReadOnly Property DeclaredOrInferredLocalOpt As LocalSymbol
Get
Return _DeclaredOrInferredLocalOpt
End Get
End Property
Private ReadOnly _ControlVariable As BoundExpression
Public ReadOnly Property ControlVariable As BoundExpression
Get
Return _ControlVariable
End Get
End Property
Private ReadOnly _Body As BoundStatement
Public ReadOnly Property Body As BoundStatement
Get
Return _Body
End Get
End Property
Private ReadOnly _NextVariablesOpt As ImmutableArray(Of BoundExpression)
Public ReadOnly Property NextVariablesOpt As ImmutableArray(Of BoundExpression)
Get
Return _NextVariablesOpt
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundForToUserDefinedOperators
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, leftOperandPlaceholder As BoundRValuePlaceholder, rightOperandPlaceholder As BoundRValuePlaceholder, addition As BoundUserDefinedBinaryOperator, subtraction As BoundUserDefinedBinaryOperator, lessThanOrEqual As BoundExpression, greaterThanOrEqual As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ForToUserDefinedOperators, syntax, hasErrors OrElse leftOperandPlaceholder.NonNullAndHasErrors() OrElse rightOperandPlaceholder.NonNullAndHasErrors() OrElse addition.NonNullAndHasErrors() OrElse subtraction.NonNullAndHasErrors() OrElse lessThanOrEqual.NonNullAndHasErrors() OrElse greaterThanOrEqual.NonNullAndHasErrors())
Debug.Assert(leftOperandPlaceholder IsNot Nothing, "Field 'leftOperandPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(rightOperandPlaceholder IsNot Nothing, "Field 'rightOperandPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(addition IsNot Nothing, "Field 'addition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(subtraction IsNot Nothing, "Field 'subtraction' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(lessThanOrEqual IsNot Nothing, "Field 'lessThanOrEqual' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(greaterThanOrEqual IsNot Nothing, "Field 'greaterThanOrEqual' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LeftOperandPlaceholder = leftOperandPlaceholder
Me._RightOperandPlaceholder = rightOperandPlaceholder
Me._Addition = addition
Me._Subtraction = subtraction
Me._LessThanOrEqual = lessThanOrEqual
Me._GreaterThanOrEqual = greaterThanOrEqual
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LeftOperandPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property LeftOperandPlaceholder As BoundRValuePlaceholder
Get
Return _LeftOperandPlaceholder
End Get
End Property
Private ReadOnly _RightOperandPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property RightOperandPlaceholder As BoundRValuePlaceholder
Get
Return _RightOperandPlaceholder
End Get
End Property
Private ReadOnly _Addition As BoundUserDefinedBinaryOperator
Public ReadOnly Property Addition As BoundUserDefinedBinaryOperator
Get
Return _Addition
End Get
End Property
Private ReadOnly _Subtraction As BoundUserDefinedBinaryOperator
Public ReadOnly Property Subtraction As BoundUserDefinedBinaryOperator
Get
Return _Subtraction
End Get
End Property
Private ReadOnly _LessThanOrEqual As BoundExpression
Public ReadOnly Property LessThanOrEqual As BoundExpression
Get
Return _LessThanOrEqual
End Get
End Property
Private ReadOnly _GreaterThanOrEqual As BoundExpression
Public ReadOnly Property GreaterThanOrEqual As BoundExpression
Get
Return _GreaterThanOrEqual
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitForToUserDefinedOperators(Me)
End Function
Public Function Update(leftOperandPlaceholder As BoundRValuePlaceholder, rightOperandPlaceholder As BoundRValuePlaceholder, addition As BoundUserDefinedBinaryOperator, subtraction As BoundUserDefinedBinaryOperator, lessThanOrEqual As BoundExpression, greaterThanOrEqual As BoundExpression) As BoundForToUserDefinedOperators
If leftOperandPlaceholder IsNot Me.LeftOperandPlaceholder OrElse rightOperandPlaceholder IsNot Me.RightOperandPlaceholder OrElse addition IsNot Me.Addition OrElse subtraction IsNot Me.Subtraction OrElse lessThanOrEqual IsNot Me.LessThanOrEqual OrElse greaterThanOrEqual IsNot Me.GreaterThanOrEqual Then
Dim result = New BoundForToUserDefinedOperators(Me.Syntax, leftOperandPlaceholder, rightOperandPlaceholder, addition, subtraction, lessThanOrEqual, greaterThanOrEqual, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundForToStatement
Inherits BoundForStatement
Public Sub New(syntax As SyntaxNode, initialValue As BoundExpression, limitValue As BoundExpression, stepValue As BoundExpression, checked As Boolean, operatorsOpt As BoundForToUserDefinedOperators, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ForToStatement, syntax, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, hasErrors OrElse initialValue.NonNullAndHasErrors() OrElse limitValue.NonNullAndHasErrors() OrElse stepValue.NonNullAndHasErrors() OrElse operatorsOpt.NonNullAndHasErrors() OrElse controlVariable.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors() OrElse nextVariablesOpt.NonNullAndHasErrors())
Debug.Assert(initialValue IsNot Nothing, "Field 'initialValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(limitValue IsNot Nothing, "Field 'limitValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(stepValue IsNot Nothing, "Field 'stepValue' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(controlVariable IsNot Nothing, "Field 'controlVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._InitialValue = initialValue
Me._LimitValue = limitValue
Me._StepValue = stepValue
Me._Checked = checked
Me._OperatorsOpt = operatorsOpt
End Sub
Private ReadOnly _InitialValue As BoundExpression
Public ReadOnly Property InitialValue As BoundExpression
Get
Return _InitialValue
End Get
End Property
Private ReadOnly _LimitValue As BoundExpression
Public ReadOnly Property LimitValue As BoundExpression
Get
Return _LimitValue
End Get
End Property
Private ReadOnly _StepValue As BoundExpression
Public ReadOnly Property StepValue As BoundExpression
Get
Return _StepValue
End Get
End Property
Private ReadOnly _Checked As Boolean
Public ReadOnly Property Checked As Boolean
Get
Return _Checked
End Get
End Property
Private ReadOnly _OperatorsOpt As BoundForToUserDefinedOperators
Public ReadOnly Property OperatorsOpt As BoundForToUserDefinedOperators
Get
Return _OperatorsOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitForToStatement(Me)
End Function
Public Function Update(initialValue As BoundExpression, limitValue As BoundExpression, stepValue As BoundExpression, checked As Boolean, operatorsOpt As BoundForToUserDefinedOperators, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundForToStatement
If initialValue IsNot Me.InitialValue OrElse limitValue IsNot Me.LimitValue OrElse stepValue IsNot Me.StepValue OrElse checked <> Me.Checked OrElse operatorsOpt IsNot Me.OperatorsOpt OrElse declaredOrInferredLocalOpt IsNot Me.DeclaredOrInferredLocalOpt OrElse controlVariable IsNot Me.ControlVariable OrElse body IsNot Me.Body OrElse nextVariablesOpt <> Me.NextVariablesOpt OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundForToStatement(Me.Syntax, initialValue, limitValue, stepValue, checked, operatorsOpt, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundForEachStatement
Inherits BoundForStatement
Public Sub New(syntax As SyntaxNode, collection As BoundExpression, enumeratorInfo As ForEachEnumeratorInfo, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ForEachStatement, syntax, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, hasErrors OrElse collection.NonNullAndHasErrors() OrElse controlVariable.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors() OrElse nextVariablesOpt.NonNullAndHasErrors())
Debug.Assert(collection IsNot Nothing, "Field 'collection' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(enumeratorInfo IsNot Nothing, "Field 'enumeratorInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(controlVariable IsNot Nothing, "Field 'controlVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(continueLabel IsNot Nothing, "Field 'continueLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(exitLabel IsNot Nothing, "Field 'exitLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Collection = collection
Me._EnumeratorInfo = enumeratorInfo
End Sub
Private ReadOnly _Collection As BoundExpression
Public ReadOnly Property Collection As BoundExpression
Get
Return _Collection
End Get
End Property
Private ReadOnly _EnumeratorInfo As ForEachEnumeratorInfo
Public ReadOnly Property EnumeratorInfo As ForEachEnumeratorInfo
Get
Return _EnumeratorInfo
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitForEachStatement(Me)
End Function
Public Function Update(collection As BoundExpression, enumeratorInfo As ForEachEnumeratorInfo, declaredOrInferredLocalOpt As LocalSymbol, controlVariable As BoundExpression, body As BoundStatement, nextVariablesOpt As ImmutableArray(Of BoundExpression), continueLabel As LabelSymbol, exitLabel As LabelSymbol) As BoundForEachStatement
If collection IsNot Me.Collection OrElse enumeratorInfo IsNot Me.EnumeratorInfo OrElse declaredOrInferredLocalOpt IsNot Me.DeclaredOrInferredLocalOpt OrElse controlVariable IsNot Me.ControlVariable OrElse body IsNot Me.Body OrElse nextVariablesOpt <> Me.NextVariablesOpt OrElse continueLabel IsNot Me.ContinueLabel OrElse exitLabel IsNot Me.ExitLabel Then
Dim result = New BoundForEachStatement(Me.Syntax, collection, enumeratorInfo, declaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, continueLabel, exitLabel, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundExitStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ExitStatement, syntax, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol)
MyBase.New(BoundKind.ExitStatement, syntax)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitExitStatement(Me)
End Function
Public Function Update(label As LabelSymbol) As BoundExitStatement
If label IsNot Me.Label Then
Dim result = New BoundExitStatement(Me.Syntax, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundContinueStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ContinueStatement, syntax, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol)
MyBase.New(BoundKind.ContinueStatement, syntax)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitContinueStatement(Me)
End Function
Public Function Update(label As LabelSymbol) As BoundContinueStatement
If label IsNot Me.Label Then
Dim result = New BoundContinueStatement(Me.Syntax, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTryStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, tryBlock As BoundBlock, catchBlocks As ImmutableArray(Of BoundCatchBlock), finallyBlockOpt As BoundBlock, exitLabelOpt As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TryStatement, syntax, hasErrors OrElse tryBlock.NonNullAndHasErrors() OrElse catchBlocks.NonNullAndHasErrors() OrElse finallyBlockOpt.NonNullAndHasErrors())
Debug.Assert(tryBlock IsNot Nothing, "Field 'tryBlock' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (catchBlocks.IsDefault), "Field 'catchBlocks' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._TryBlock = tryBlock
Me._CatchBlocks = catchBlocks
Me._FinallyBlockOpt = finallyBlockOpt
Me._ExitLabelOpt = exitLabelOpt
End Sub
Private ReadOnly _TryBlock As BoundBlock
Public ReadOnly Property TryBlock As BoundBlock
Get
Return _TryBlock
End Get
End Property
Private ReadOnly _CatchBlocks As ImmutableArray(Of BoundCatchBlock)
Public ReadOnly Property CatchBlocks As ImmutableArray(Of BoundCatchBlock)
Get
Return _CatchBlocks
End Get
End Property
Private ReadOnly _FinallyBlockOpt As BoundBlock
Public ReadOnly Property FinallyBlockOpt As BoundBlock
Get
Return _FinallyBlockOpt
End Get
End Property
Private ReadOnly _ExitLabelOpt As LabelSymbol
Public ReadOnly Property ExitLabelOpt As LabelSymbol
Get
Return _ExitLabelOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTryStatement(Me)
End Function
Public Function Update(tryBlock As BoundBlock, catchBlocks As ImmutableArray(Of BoundCatchBlock), finallyBlockOpt As BoundBlock, exitLabelOpt As LabelSymbol) As BoundTryStatement
If tryBlock IsNot Me.TryBlock OrElse catchBlocks <> Me.CatchBlocks OrElse finallyBlockOpt IsNot Me.FinallyBlockOpt OrElse exitLabelOpt IsNot Me.ExitLabelOpt Then
Dim result = New BoundTryStatement(Me.Syntax, tryBlock, catchBlocks, finallyBlockOpt, exitLabelOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundCatchBlock
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, localOpt As LocalSymbol, exceptionSourceOpt As BoundExpression, errorLineNumberOpt As BoundExpression, exceptionFilterOpt As BoundExpression, body As BoundBlock, isSynthesizedAsyncCatchAll As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.CatchBlock, syntax, hasErrors OrElse exceptionSourceOpt.NonNullAndHasErrors() OrElse errorLineNumberOpt.NonNullAndHasErrors() OrElse exceptionFilterOpt.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalOpt = localOpt
Me._ExceptionSourceOpt = exceptionSourceOpt
Me._ErrorLineNumberOpt = errorLineNumberOpt
Me._ExceptionFilterOpt = exceptionFilterOpt
Me._Body = body
Me._IsSynthesizedAsyncCatchAll = isSynthesizedAsyncCatchAll
End Sub
Private ReadOnly _LocalOpt As LocalSymbol
Public ReadOnly Property LocalOpt As LocalSymbol
Get
Return _LocalOpt
End Get
End Property
Private ReadOnly _ExceptionSourceOpt As BoundExpression
Public ReadOnly Property ExceptionSourceOpt As BoundExpression
Get
Return _ExceptionSourceOpt
End Get
End Property
Private ReadOnly _ErrorLineNumberOpt As BoundExpression
Public ReadOnly Property ErrorLineNumberOpt As BoundExpression
Get
Return _ErrorLineNumberOpt
End Get
End Property
Private ReadOnly _ExceptionFilterOpt As BoundExpression
Public ReadOnly Property ExceptionFilterOpt As BoundExpression
Get
Return _ExceptionFilterOpt
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _IsSynthesizedAsyncCatchAll As Boolean
Public ReadOnly Property IsSynthesizedAsyncCatchAll As Boolean
Get
Return _IsSynthesizedAsyncCatchAll
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitCatchBlock(Me)
End Function
Public Function Update(localOpt As LocalSymbol, exceptionSourceOpt As BoundExpression, errorLineNumberOpt As BoundExpression, exceptionFilterOpt As BoundExpression, body As BoundBlock, isSynthesizedAsyncCatchAll As Boolean) As BoundCatchBlock
If localOpt IsNot Me.LocalOpt OrElse exceptionSourceOpt IsNot Me.ExceptionSourceOpt OrElse errorLineNumberOpt IsNot Me.ErrorLineNumberOpt OrElse exceptionFilterOpt IsNot Me.ExceptionFilterOpt OrElse body IsNot Me.Body OrElse isSynthesizedAsyncCatchAll <> Me.IsSynthesizedAsyncCatchAll Then
Dim result = New BoundCatchBlock(Me.Syntax, localOpt, exceptionSourceOpt, errorLineNumberOpt, exceptionFilterOpt, body, isSynthesizedAsyncCatchAll, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLiteral
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, value As ConstantValue, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Literal, syntax, type, hasErrors)
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, value As ConstantValue, type As TypeSymbol)
MyBase.New(BoundKind.Literal, syntax, type)
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Validate()
End Sub
Private ReadOnly _Value As ConstantValue
Public ReadOnly Property Value As ConstantValue
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLiteral(Me)
End Function
Public Function Update(value As ConstantValue, type As TypeSymbol) As BoundLiteral
If value IsNot Me.Value OrElse type IsNot Me.Type Then
Dim result = New BoundLiteral(Me.Syntax, value, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMeReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MeReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MeReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMeReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMeReference
If type IsNot Me.Type Then
Dim result = New BoundMeReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundValueTypeMeReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ValueTypeMeReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.ValueTypeMeReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Validate()
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitValueTypeMeReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundValueTypeMeReference
If type IsNot Me.Type Then
Dim result = New BoundValueTypeMeReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMyBaseReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MyBaseReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MyBaseReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMyBaseReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMyBaseReference
If type IsNot Me.Type Then
Dim result = New BoundMyBaseReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundMyClassReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.MyClassReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.MyClassReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMyClassReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundMyClassReference
If type IsNot Me.Type Then
Dim result = New BoundMyClassReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPreviousSubmissionReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, sourceType As NamedTypeSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.PreviousSubmissionReference, syntax, type, hasErrors)
Debug.Assert(sourceType IsNot Nothing, "Field 'sourceType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._SourceType = sourceType
End Sub
Public Sub New(syntax As SyntaxNode, sourceType As NamedTypeSymbol, type As TypeSymbol)
MyBase.New(BoundKind.PreviousSubmissionReference, syntax, type)
Debug.Assert(sourceType IsNot Nothing, "Field 'sourceType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._SourceType = sourceType
End Sub
Private ReadOnly _SourceType As NamedTypeSymbol
Public ReadOnly Property SourceType As NamedTypeSymbol
Get
Return _SourceType
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPreviousSubmissionReference(Me)
End Function
Public Function Update(sourceType As NamedTypeSymbol, type As TypeSymbol) As BoundPreviousSubmissionReference
If sourceType IsNot Me.SourceType OrElse type IsNot Me.Type Then
Dim result = New BoundPreviousSubmissionReference(Me.Syntax, sourceType, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundHostObjectMemberReference
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.HostObjectMemberReference, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Public Sub New(syntax As SyntaxNode, type As TypeSymbol)
MyBase.New(BoundKind.HostObjectMemberReference, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitHostObjectMemberReference(Me)
End Function
Public Function Update(type As TypeSymbol) As BoundHostObjectMemberReference
If type IsNot Me.Type Then
Dim result = New BoundHostObjectMemberReference(Me.Syntax, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLocal
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Local, syntax, type, hasErrors)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.Local, syntax, type)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Validate()
End Sub
Private ReadOnly _LocalSymbol As LocalSymbol
Public ReadOnly Property LocalSymbol As LocalSymbol
Get
Return _LocalSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLocal(Me)
End Function
Public Function Update(localSymbol As LocalSymbol, isLValue As Boolean, type As TypeSymbol) As BoundLocal
If localSymbol IsNot Me.LocalSymbol OrElse isLValue <> Me.IsLValue OrElse type IsNot Me.Type Then
Dim result = New BoundLocal(Me.Syntax, localSymbol, isLValue, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundPseudoVariable
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, emitExpressions As PseudoVariableExpressions, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.PseudoVariable, syntax, type, hasErrors)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(emitExpressions IsNot Nothing, "Field 'emitExpressions' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Me._EmitExpressions = emitExpressions
End Sub
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, isLValue As Boolean, emitExpressions As PseudoVariableExpressions, type As TypeSymbol)
MyBase.New(BoundKind.PseudoVariable, syntax, type)
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(emitExpressions IsNot Nothing, "Field 'emitExpressions' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LocalSymbol = localSymbol
Me._IsLValue = isLValue
Me._EmitExpressions = emitExpressions
End Sub
Private ReadOnly _LocalSymbol As LocalSymbol
Public ReadOnly Property LocalSymbol As LocalSymbol
Get
Return _LocalSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _EmitExpressions As PseudoVariableExpressions
Public ReadOnly Property EmitExpressions As PseudoVariableExpressions
Get
Return _EmitExpressions
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitPseudoVariable(Me)
End Function
Public Function Update(localSymbol As LocalSymbol, isLValue As Boolean, emitExpressions As PseudoVariableExpressions, type As TypeSymbol) As BoundPseudoVariable
If localSymbol IsNot Me.LocalSymbol OrElse isLValue <> Me.IsLValue OrElse emitExpressions IsNot Me.EmitExpressions OrElse type IsNot Me.Type Then
Dim result = New BoundPseudoVariable(Me.Syntax, localSymbol, isLValue, emitExpressions, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundParameter
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Parameter, syntax, type, hasErrors)
Debug.Assert(parameterSymbol IsNot Nothing, "Field 'parameterSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ParameterSymbol = parameterSymbol
Me._IsLValue = isLValue
Me._SuppressVirtualCalls = suppressVirtualCalls
End Sub
Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.Parameter, syntax, type)
Debug.Assert(parameterSymbol IsNot Nothing, "Field 'parameterSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ParameterSymbol = parameterSymbol
Me._IsLValue = isLValue
Me._SuppressVirtualCalls = suppressVirtualCalls
End Sub
Private ReadOnly _ParameterSymbol As ParameterSymbol
Public ReadOnly Property ParameterSymbol As ParameterSymbol
Get
Return _ParameterSymbol
End Get
End Property
Private ReadOnly _IsLValue As Boolean
Public Overrides ReadOnly Property IsLValue As Boolean
Get
Return _IsLValue
End Get
End Property
Private ReadOnly _SuppressVirtualCalls As Boolean
Public Overrides ReadOnly Property SuppressVirtualCalls As Boolean
Get
Return _SuppressVirtualCalls
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitParameter(Me)
End Function
Public Function Update(parameterSymbol As ParameterSymbol, isLValue As Boolean, suppressVirtualCalls As Boolean, type As TypeSymbol) As BoundParameter
If parameterSymbol IsNot Me.ParameterSymbol OrElse isLValue <> Me.IsLValue OrElse suppressVirtualCalls <> Me.SuppressVirtualCalls OrElse type IsNot Me.Type Then
Dim result = New BoundParameter(Me.Syntax, parameterSymbol, isLValue, suppressVirtualCalls, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundByRefArgumentPlaceholder
Inherits BoundValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, isOut As Boolean, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ByRefArgumentPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsOut = isOut
End Sub
Public Sub New(syntax As SyntaxNode, isOut As Boolean, type As TypeSymbol)
MyBase.New(BoundKind.ByRefArgumentPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._IsOut = isOut
End Sub
Private ReadOnly _IsOut As Boolean
Public ReadOnly Property IsOut As Boolean
Get
Return _IsOut
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitByRefArgumentPlaceholder(Me)
End Function
Public Function Update(isOut As Boolean, type As TypeSymbol) As BoundByRefArgumentPlaceholder
If isOut <> Me.IsOut OrElse type IsNot Me.Type Then
Dim result = New BoundByRefArgumentPlaceholder(Me.Syntax, isOut, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundByRefArgumentWithCopyBack
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, originalArgument As BoundExpression, inConversion As BoundExpression, inPlaceholder As BoundByRefArgumentPlaceholder, outConversion As BoundExpression, outPlaceholder As BoundRValuePlaceholder, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ByRefArgumentWithCopyBack, syntax, type, hasErrors OrElse originalArgument.NonNullAndHasErrors() OrElse inConversion.NonNullAndHasErrors() OrElse inPlaceholder.NonNullAndHasErrors() OrElse outConversion.NonNullAndHasErrors() OrElse outPlaceholder.NonNullAndHasErrors())
Debug.Assert(originalArgument IsNot Nothing, "Field 'originalArgument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(inConversion IsNot Nothing, "Field 'inConversion' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(inPlaceholder IsNot Nothing, "Field 'inPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(outConversion IsNot Nothing, "Field 'outConversion' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(outPlaceholder IsNot Nothing, "Field 'outPlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OriginalArgument = originalArgument
Me._InConversion = inConversion
Me._InPlaceholder = inPlaceholder
Me._OutConversion = outConversion
Me._OutPlaceholder = outPlaceholder
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OriginalArgument As BoundExpression
Public ReadOnly Property OriginalArgument As BoundExpression
Get
Return _OriginalArgument
End Get
End Property
Private ReadOnly _InConversion As BoundExpression
Public ReadOnly Property InConversion As BoundExpression
Get
Return _InConversion
End Get
End Property
Private ReadOnly _InPlaceholder As BoundByRefArgumentPlaceholder
Public ReadOnly Property InPlaceholder As BoundByRefArgumentPlaceholder
Get
Return _InPlaceholder
End Get
End Property
Private ReadOnly _OutConversion As BoundExpression
Public ReadOnly Property OutConversion As BoundExpression
Get
Return _OutConversion
End Get
End Property
Private ReadOnly _OutPlaceholder As BoundRValuePlaceholder
Public ReadOnly Property OutPlaceholder As BoundRValuePlaceholder
Get
Return _OutPlaceholder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitByRefArgumentWithCopyBack(Me)
End Function
Public Function Update(originalArgument As BoundExpression, inConversion As BoundExpression, inPlaceholder As BoundByRefArgumentPlaceholder, outConversion As BoundExpression, outPlaceholder As BoundRValuePlaceholder, type As TypeSymbol) As BoundByRefArgumentWithCopyBack
If originalArgument IsNot Me.OriginalArgument OrElse inConversion IsNot Me.InConversion OrElse inPlaceholder IsNot Me.InPlaceholder OrElse outConversion IsNot Me.OutConversion OrElse outPlaceholder IsNot Me.OutPlaceholder OrElse type IsNot Me.Type Then
Dim result = New BoundByRefArgumentWithCopyBack(Me.Syntax, originalArgument, inConversion, inPlaceholder, outConversion, outPlaceholder, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLateBoundArgumentSupportingAssignmentWithCapture
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, originalArgument As BoundExpression, localSymbol As SynthesizedLocal, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LateBoundArgumentSupportingAssignmentWithCapture, syntax, type, hasErrors OrElse originalArgument.NonNullAndHasErrors())
Debug.Assert(originalArgument IsNot Nothing, "Field 'originalArgument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(localSymbol IsNot Nothing, "Field 'localSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OriginalArgument = originalArgument
Me._LocalSymbol = localSymbol
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OriginalArgument As BoundExpression
Public ReadOnly Property OriginalArgument As BoundExpression
Get
Return _OriginalArgument
End Get
End Property
Private ReadOnly _LocalSymbol As SynthesizedLocal
Public ReadOnly Property LocalSymbol As SynthesizedLocal
Get
Return _LocalSymbol
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLateBoundArgumentSupportingAssignmentWithCapture(Me)
End Function
Public Function Update(originalArgument As BoundExpression, localSymbol As SynthesizedLocal, type As TypeSymbol) As BoundLateBoundArgumentSupportingAssignmentWithCapture
If originalArgument IsNot Me.OriginalArgument OrElse localSymbol IsNot Me.LocalSymbol OrElse type IsNot Me.Type Then
Dim result = New BoundLateBoundArgumentSupportingAssignmentWithCapture(Me.Syntax, originalArgument, localSymbol, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLabelStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.LabelStatement, syntax, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol)
MyBase.New(BoundKind.LabelStatement, syntax)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLabelStatement(Me)
End Function
Public Function Update(label As LabelSymbol) As BoundLabelStatement
If label IsNot Me.Label Then
Dim result = New BoundLabelStatement(Me.Syntax, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLabel
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.Label, syntax, type, hasErrors)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, type As TypeSymbol)
MyBase.New(BoundKind.Label, syntax, type)
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLabel(Me)
End Function
Public Function Update(label As LabelSymbol, type As TypeSymbol) As BoundLabel
If label IsNot Me.Label OrElse type IsNot Me.Type Then
Dim result = New BoundLabel(Me.Syntax, label, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGotoStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, label As LabelSymbol, labelExpressionOpt As BoundLabel, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GotoStatement, syntax, hasErrors OrElse labelExpressionOpt.NonNullAndHasErrors())
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Label = label
Me._LabelExpressionOpt = labelExpressionOpt
End Sub
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
Private ReadOnly _LabelExpressionOpt As BoundLabel
Public ReadOnly Property LabelExpressionOpt As BoundLabel
Get
Return _LabelExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGotoStatement(Me)
End Function
Public Function Update(label As LabelSymbol, labelExpressionOpt As BoundLabel) As BoundGotoStatement
If label IsNot Me.Label OrElse labelExpressionOpt IsNot Me.LabelExpressionOpt Then
Dim result = New BoundGotoStatement(Me.Syntax, label, labelExpressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundStatementList
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, statements As ImmutableArray(Of BoundStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.StatementList, syntax, hasErrors OrElse statements.NonNullAndHasErrors())
Debug.Assert(Not (statements.IsDefault), "Field 'statements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Statements = statements
End Sub
Private ReadOnly _Statements As ImmutableArray(Of BoundStatement)
Public ReadOnly Property Statements As ImmutableArray(Of BoundStatement)
Get
Return _Statements
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitStatementList(Me)
End Function
Public Function Update(statements As ImmutableArray(Of BoundStatement)) As BoundStatementList
If statements <> Me.Statements Then
Dim result = New BoundStatementList(Me.Syntax, statements, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConditionalGoto
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, condition As BoundExpression, jumpIfTrue As Boolean, label As LabelSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConditionalGoto, syntax, hasErrors OrElse condition.NonNullAndHasErrors())
Debug.Assert(condition IsNot Nothing, "Field 'condition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(label IsNot Nothing, "Field 'label' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Condition = condition
Me._JumpIfTrue = jumpIfTrue
Me._Label = label
End Sub
Private ReadOnly _Condition As BoundExpression
Public ReadOnly Property Condition As BoundExpression
Get
Return _Condition
End Get
End Property
Private ReadOnly _JumpIfTrue As Boolean
Public ReadOnly Property JumpIfTrue As Boolean
Get
Return _JumpIfTrue
End Get
End Property
Private ReadOnly _Label As LabelSymbol
Public ReadOnly Property Label As LabelSymbol
Get
Return _Label
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConditionalGoto(Me)
End Function
Public Function Update(condition As BoundExpression, jumpIfTrue As Boolean, label As LabelSymbol) As BoundConditionalGoto
If condition IsNot Me.Condition OrElse jumpIfTrue <> Me.JumpIfTrue OrElse label IsNot Me.Label Then
Dim result = New BoundConditionalGoto(Me.Syntax, condition, jumpIfTrue, label, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundWithStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, originalExpression As BoundExpression, body As BoundBlock, binder As WithBlockBinder, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.WithStatement, syntax, hasErrors OrElse originalExpression.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(originalExpression IsNot Nothing, "Field 'originalExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._OriginalExpression = originalExpression
Me._Body = body
Me._Binder = binder
End Sub
Private ReadOnly _OriginalExpression As BoundExpression
Public ReadOnly Property OriginalExpression As BoundExpression
Get
Return _OriginalExpression
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _Binder As WithBlockBinder
Public ReadOnly Property Binder As WithBlockBinder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitWithStatement(Me)
End Function
Public Function Update(originalExpression As BoundExpression, body As BoundBlock, binder As WithBlockBinder) As BoundWithStatement
If originalExpression IsNot Me.OriginalExpression OrElse body IsNot Me.Body OrElse binder IsNot Me.Binder Then
Dim result = New BoundWithStatement(Me.Syntax, originalExpression, body, binder, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class UnboundLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, flags As SourceMemberFlags, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol, bindingCache As UnboundLambda.UnboundLambdaBindingCache, hasErrors As Boolean)
MyBase.New(BoundKind.UnboundLambda, syntax, Nothing, hasErrors)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(bindingCache IsNot Nothing, "Field 'bindingCache' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Flags = flags
Me._Parameters = parameters
Me._ReturnType = returnType
Me._BindingCache = bindingCache
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, binder As Binder, flags As SourceMemberFlags, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol, bindingCache As UnboundLambda.UnboundLambdaBindingCache)
MyBase.New(BoundKind.UnboundLambda, syntax, Nothing)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(bindingCache IsNot Nothing, "Field 'bindingCache' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Flags = flags
Me._Parameters = parameters
Me._ReturnType = returnType
Me._BindingCache = bindingCache
Validate()
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _Flags As SourceMemberFlags
Public ReadOnly Property Flags As SourceMemberFlags
Get
Return _Flags
End Get
End Property
Private ReadOnly _Parameters As ImmutableArray(Of ParameterSymbol)
Public ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _Parameters
End Get
End Property
Private ReadOnly _ReturnType As TypeSymbol
Public ReadOnly Property ReturnType As TypeSymbol
Get
Return _ReturnType
End Get
End Property
Private ReadOnly _BindingCache As UnboundLambda.UnboundLambdaBindingCache
Public ReadOnly Property BindingCache As UnboundLambda.UnboundLambdaBindingCache
Get
Return _BindingCache
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnboundLambda(Me)
End Function
Public Function Update(binder As Binder, flags As SourceMemberFlags, parameters As ImmutableArray(Of ParameterSymbol), returnType As TypeSymbol, bindingCache As UnboundLambda.UnboundLambdaBindingCache) As UnboundLambda
If binder IsNot Me.Binder OrElse flags <> Me.Flags OrElse parameters <> Me.Parameters OrElse returnType IsNot Me.ReturnType OrElse bindingCache IsNot Me.BindingCache Then
Dim result = New UnboundLambda(Me.Syntax, binder, flags, parameters, returnType, bindingCache, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, lambdaSymbol As LambdaSymbol, body As BoundBlock, diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol), lambdaBinderOpt As LambdaBodyBinder, delegateRelaxation As ConversionKind, methodConversionKind As MethodConversionKind, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Lambda, syntax, Nothing, hasErrors OrElse body.NonNullAndHasErrors())
Debug.Assert(lambdaSymbol IsNot Nothing, "Field 'lambdaSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LambdaSymbol = lambdaSymbol
Me._Body = body
Me._Diagnostics = diagnostics
Me._LambdaBinderOpt = lambdaBinderOpt
Me._DelegateRelaxation = delegateRelaxation
Me._MethodConversionKind = methodConversionKind
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _LambdaSymbol As LambdaSymbol
Public ReadOnly Property LambdaSymbol As LambdaSymbol
Get
Return _LambdaSymbol
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Public ReadOnly Property Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Get
Return _Diagnostics
End Get
End Property
Private ReadOnly _LambdaBinderOpt As LambdaBodyBinder
Public ReadOnly Property LambdaBinderOpt As LambdaBodyBinder
Get
Return _LambdaBinderOpt
End Get
End Property
Private ReadOnly _DelegateRelaxation As ConversionKind
Public ReadOnly Property DelegateRelaxation As ConversionKind
Get
Return _DelegateRelaxation
End Get
End Property
Private ReadOnly _MethodConversionKind As MethodConversionKind
Public ReadOnly Property MethodConversionKind As MethodConversionKind
Get
Return _MethodConversionKind
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLambda(Me)
End Function
Public Function Update(lambdaSymbol As LambdaSymbol, body As BoundBlock, diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol), lambdaBinderOpt As LambdaBodyBinder, delegateRelaxation As ConversionKind, methodConversionKind As MethodConversionKind) As BoundLambda
If lambdaSymbol IsNot Me.LambdaSymbol OrElse body IsNot Me.Body OrElse diagnostics <> Me.Diagnostics OrElse lambdaBinderOpt IsNot Me.LambdaBinderOpt OrElse delegateRelaxation <> Me.DelegateRelaxation OrElse methodConversionKind <> Me.MethodConversionKind Then
Dim result = New BoundLambda(Me.Syntax, lambdaSymbol, body, diagnostics, lambdaBinderOpt, delegateRelaxation, methodConversionKind, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundQueryExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, lastOperator As BoundQueryClauseBase, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryExpression, syntax, type, hasErrors OrElse lastOperator.NonNullAndHasErrors())
Debug.Assert(lastOperator IsNot Nothing, "Field 'lastOperator' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LastOperator = lastOperator
End Sub
Private ReadOnly _LastOperator As BoundQueryClauseBase
Public ReadOnly Property LastOperator As BoundQueryClauseBase
Get
Return _LastOperator
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryExpression(Me)
End Function
Public Function Update(lastOperator As BoundQueryClauseBase, type As TypeSymbol) As BoundQueryExpression
If lastOperator IsNot Me.LastOperator OrElse type IsNot Me.Type Then
Dim result = New BoundQueryExpression(Me.Syntax, lastOperator, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundQueryPart
Inherits BoundExpression
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
End Class
Partial Friend NotInheritable Class BoundQuerySource
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QuerySource, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQuerySource(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundQuerySource
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundQuerySource(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundToQueryableCollectionConversion
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, conversionCall As BoundCall, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ToQueryableCollectionConversion, syntax, type, hasErrors OrElse conversionCall.NonNullAndHasErrors())
Debug.Assert(conversionCall IsNot Nothing, "Field 'conversionCall' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ConversionCall = conversionCall
End Sub
Private ReadOnly _ConversionCall As BoundCall
Public ReadOnly Property ConversionCall As BoundCall
Get
Return _ConversionCall
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitToQueryableCollectionConversion(Me)
End Function
Public Function Update(conversionCall As BoundCall, type As TypeSymbol) As BoundToQueryableCollectionConversion
If conversionCall IsNot Me.ConversionCall OrElse type IsNot Me.Type Then
Dim result = New BoundToQueryableCollectionConversion(Me.Syntax, conversionCall, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundQueryClauseBase
Inherits BoundQueryPart
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, hasErrors As Boolean)
MyBase.New(kind, syntax, type, hasErrors)
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariables = rangeVariables
Me._CompoundVariableType = compoundVariableType
Me._Binders = binders
End Sub
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol)
MyBase.New(kind, syntax, type)
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariables = rangeVariables
Me._CompoundVariableType = compoundVariableType
Me._Binders = binders
End Sub
Private ReadOnly _RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Public ReadOnly Property RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Get
Return _RangeVariables
End Get
End Property
Private ReadOnly _CompoundVariableType As TypeSymbol
Public ReadOnly Property CompoundVariableType As TypeSymbol
Get
Return _CompoundVariableType
End Get
End Property
Private ReadOnly _Binders As ImmutableArray(Of Binder)
Public ReadOnly Property Binders As ImmutableArray(Of Binder)
Get
Return _Binders
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundQueryableSource
Inherits BoundQueryClauseBase
Public Sub New(syntax As SyntaxNode, source As BoundQueryPart, rangeVariableOpt As RangeVariableSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryableSource, syntax, rangeVariables, compoundVariableType, binders, type, hasErrors OrElse source.NonNullAndHasErrors())
Debug.Assert(source IsNot Nothing, "Field 'source' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Source = source
Me._RangeVariableOpt = rangeVariableOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Source As BoundQueryPart
Public ReadOnly Property Source As BoundQueryPart
Get
Return _Source
End Get
End Property
Private ReadOnly _RangeVariableOpt As RangeVariableSymbol
Public ReadOnly Property RangeVariableOpt As RangeVariableSymbol
Get
Return _RangeVariableOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryableSource(Me)
End Function
Public Function Update(source As BoundQueryPart, rangeVariableOpt As RangeVariableSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol) As BoundQueryableSource
If source IsNot Me.Source OrElse rangeVariableOpt IsNot Me.RangeVariableOpt OrElse rangeVariables <> Me.RangeVariables OrElse compoundVariableType IsNot Me.CompoundVariableType OrElse binders <> Me.Binders OrElse type IsNot Me.Type Then
Dim result = New BoundQueryableSource(Me.Syntax, source, rangeVariableOpt, rangeVariables, compoundVariableType, binders, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundQueryClause
Inherits BoundQueryClauseBase
Public Sub New(syntax As SyntaxNode, underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryClause, syntax, rangeVariables, compoundVariableType, binders, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingExpression = underlyingExpression
End Sub
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryClause(Me)
End Function
Public Function Update(underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol) As BoundQueryClause
If underlyingExpression IsNot Me.UnderlyingExpression OrElse rangeVariables <> Me.RangeVariables OrElse compoundVariableType IsNot Me.CompoundVariableType OrElse binders <> Me.Binders OrElse type IsNot Me.Type Then
Dim result = New BoundQueryClause(Me.Syntax, underlyingExpression, rangeVariables, compoundVariableType, binders, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundOrdering
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, underlyingExpression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Ordering, syntax, type, hasErrors OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._UnderlyingExpression = underlyingExpression
End Sub
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitOrdering(Me)
End Function
Public Function Update(underlyingExpression As BoundExpression, type As TypeSymbol) As BoundOrdering
If underlyingExpression IsNot Me.UnderlyingExpression OrElse type IsNot Me.Type Then
Dim result = New BoundOrdering(Me.Syntax, underlyingExpression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundQueryLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, lambdaSymbol As SynthesizedLambdaSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), expression As BoundExpression, exprIsOperandOfConditionalBranch As Boolean, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.QueryLambda, syntax, Nothing, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(lambdaSymbol IsNot Nothing, "Field 'lambdaSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LambdaSymbol = lambdaSymbol
Me._RangeVariables = rangeVariables
Me._Expression = expression
Me._ExprIsOperandOfConditionalBranch = exprIsOperandOfConditionalBranch
End Sub
Private ReadOnly _LambdaSymbol As SynthesizedLambdaSymbol
Public ReadOnly Property LambdaSymbol As SynthesizedLambdaSymbol
Get
Return _LambdaSymbol
End Get
End Property
Private ReadOnly _RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Public ReadOnly Property RangeVariables As ImmutableArray(Of RangeVariableSymbol)
Get
Return _RangeVariables
End Get
End Property
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _ExprIsOperandOfConditionalBranch As Boolean
Public ReadOnly Property ExprIsOperandOfConditionalBranch As Boolean
Get
Return _ExprIsOperandOfConditionalBranch
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitQueryLambda(Me)
End Function
Public Function Update(lambdaSymbol As SynthesizedLambdaSymbol, rangeVariables As ImmutableArray(Of RangeVariableSymbol), expression As BoundExpression, exprIsOperandOfConditionalBranch As Boolean) As BoundQueryLambda
If lambdaSymbol IsNot Me.LambdaSymbol OrElse rangeVariables <> Me.RangeVariables OrElse expression IsNot Me.Expression OrElse exprIsOperandOfConditionalBranch <> Me.ExprIsOperandOfConditionalBranch Then
Dim result = New BoundQueryLambda(Me.Syntax, lambdaSymbol, rangeVariables, expression, exprIsOperandOfConditionalBranch, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRangeVariableAssignment
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, rangeVariable As RangeVariableSymbol, value As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RangeVariableAssignment, syntax, type, hasErrors OrElse value.NonNullAndHasErrors())
Debug.Assert(rangeVariable IsNot Nothing, "Field 'rangeVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariable = rangeVariable
Me._Value = value
End Sub
Private ReadOnly _RangeVariable As RangeVariableSymbol
Public ReadOnly Property RangeVariable As RangeVariableSymbol
Get
Return _RangeVariable
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRangeVariableAssignment(Me)
End Function
Public Function Update(rangeVariable As RangeVariableSymbol, value As BoundExpression, type As TypeSymbol) As BoundRangeVariableAssignment
If rangeVariable IsNot Me.RangeVariable OrElse value IsNot Me.Value OrElse type IsNot Me.Type Then
Dim result = New BoundRangeVariableAssignment(Me.Syntax, rangeVariable, value, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class GroupTypeInferenceLambda
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, binder As Binder, parameters As ImmutableArray(Of ParameterSymbol), compilation As VisualBasicCompilation, hasErrors As Boolean)
MyBase.New(BoundKind.GroupTypeInferenceLambda, syntax, Nothing, hasErrors)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compilation IsNot Nothing, "Field 'compilation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Parameters = parameters
Me._Compilation = compilation
End Sub
Public Sub New(syntax As SyntaxNode, binder As Binder, parameters As ImmutableArray(Of ParameterSymbol), compilation As VisualBasicCompilation)
MyBase.New(BoundKind.GroupTypeInferenceLambda, syntax, Nothing)
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (parameters.IsDefault), "Field 'parameters' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compilation IsNot Nothing, "Field 'compilation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Binder = binder
Me._Parameters = parameters
Me._Compilation = compilation
End Sub
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
Private ReadOnly _Parameters As ImmutableArray(Of ParameterSymbol)
Public ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _Parameters
End Get
End Property
Private ReadOnly _Compilation As VisualBasicCompilation
Public ReadOnly Property Compilation As VisualBasicCompilation
Get
Return _Compilation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGroupTypeInferenceLambda(Me)
End Function
Public Function Update(binder As Binder, parameters As ImmutableArray(Of ParameterSymbol), compilation As VisualBasicCompilation) As GroupTypeInferenceLambda
If binder IsNot Me.Binder OrElse parameters <> Me.Parameters OrElse compilation IsNot Me.Compilation Then
Dim result = New GroupTypeInferenceLambda(Me.Syntax, binder, parameters, compilation, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAggregateClause
Inherits BoundQueryClauseBase
Public Sub New(syntax As SyntaxNode, capturedGroupOpt As BoundQueryClauseBase, groupPlaceholderOpt As BoundRValuePlaceholder, underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AggregateClause, syntax, rangeVariables, compoundVariableType, binders, type, hasErrors OrElse capturedGroupOpt.NonNullAndHasErrors() OrElse groupPlaceholderOpt.NonNullAndHasErrors() OrElse underlyingExpression.NonNullAndHasErrors())
Debug.Assert(underlyingExpression IsNot Nothing, "Field 'underlyingExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (rangeVariables.IsDefault), "Field 'rangeVariables' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(compoundVariableType IsNot Nothing, "Field 'compoundVariableType' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (binders.IsDefault), "Field 'binders' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._CapturedGroupOpt = capturedGroupOpt
Me._GroupPlaceholderOpt = groupPlaceholderOpt
Me._UnderlyingExpression = underlyingExpression
End Sub
Private ReadOnly _CapturedGroupOpt As BoundQueryClauseBase
Public ReadOnly Property CapturedGroupOpt As BoundQueryClauseBase
Get
Return _CapturedGroupOpt
End Get
End Property
Private ReadOnly _GroupPlaceholderOpt As BoundRValuePlaceholder
Public ReadOnly Property GroupPlaceholderOpt As BoundRValuePlaceholder
Get
Return _GroupPlaceholderOpt
End Get
End Property
Private ReadOnly _UnderlyingExpression As BoundExpression
Public ReadOnly Property UnderlyingExpression As BoundExpression
Get
Return _UnderlyingExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAggregateClause(Me)
End Function
Public Function Update(capturedGroupOpt As BoundQueryClauseBase, groupPlaceholderOpt As BoundRValuePlaceholder, underlyingExpression As BoundExpression, rangeVariables As ImmutableArray(Of RangeVariableSymbol), compoundVariableType As TypeSymbol, binders As ImmutableArray(Of Binder), type As TypeSymbol) As BoundAggregateClause
If capturedGroupOpt IsNot Me.CapturedGroupOpt OrElse groupPlaceholderOpt IsNot Me.GroupPlaceholderOpt OrElse underlyingExpression IsNot Me.UnderlyingExpression OrElse rangeVariables <> Me.RangeVariables OrElse compoundVariableType IsNot Me.CompoundVariableType OrElse binders <> Me.Binders OrElse type IsNot Me.Type Then
Dim result = New BoundAggregateClause(Me.Syntax, capturedGroupOpt, groupPlaceholderOpt, underlyingExpression, rangeVariables, compoundVariableType, binders, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundGroupAggregation
Inherits BoundQueryPart
Public Sub New(syntax As SyntaxNode, group As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.GroupAggregation, syntax, type, hasErrors OrElse group.NonNullAndHasErrors())
Debug.Assert(group IsNot Nothing, "Field 'group' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Group = group
End Sub
Private ReadOnly _Group As BoundExpression
Public ReadOnly Property Group As BoundExpression
Get
Return _Group
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitGroupAggregation(Me)
End Function
Public Function Update(group As BoundExpression, type As TypeSymbol) As BoundGroupAggregation
If group IsNot Me.Group OrElse type IsNot Me.Type Then
Dim result = New BoundGroupAggregation(Me.Syntax, group, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRangeVariable
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, rangeVariable As RangeVariableSymbol, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.RangeVariable, syntax, type, hasErrors)
Debug.Assert(rangeVariable IsNot Nothing, "Field 'rangeVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariable = rangeVariable
End Sub
Public Sub New(syntax As SyntaxNode, rangeVariable As RangeVariableSymbol, type As TypeSymbol)
MyBase.New(BoundKind.RangeVariable, syntax, type)
Debug.Assert(rangeVariable IsNot Nothing, "Field 'rangeVariable' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._RangeVariable = rangeVariable
End Sub
Private ReadOnly _RangeVariable As RangeVariableSymbol
Public ReadOnly Property RangeVariable As RangeVariableSymbol
Get
Return _RangeVariable
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRangeVariable(Me)
End Function
Public Function Update(rangeVariable As RangeVariableSymbol, type As TypeSymbol) As BoundRangeVariable
If rangeVariable IsNot Me.RangeVariable OrElse type IsNot Me.Type Then
Dim result = New BoundRangeVariable(Me.Syntax, rangeVariable, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend MustInherit Class BoundAddRemoveHandlerStatement
Inherits BoundStatement
Protected Sub New(kind As BoundKind, syntax as SyntaxNode, eventAccess As BoundExpression, handler As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(kind, syntax, hasErrors)
Debug.Assert(eventAccess IsNot Nothing, "Field 'eventAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(handler IsNot Nothing, "Field 'handler' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._EventAccess = eventAccess
Me._Handler = handler
End Sub
Private ReadOnly _EventAccess As BoundExpression
Public ReadOnly Property EventAccess As BoundExpression
Get
Return _EventAccess
End Get
End Property
Private ReadOnly _Handler As BoundExpression
Public ReadOnly Property Handler As BoundExpression
Get
Return _Handler
End Get
End Property
End Class
Partial Friend NotInheritable Class BoundAddHandlerStatement
Inherits BoundAddRemoveHandlerStatement
Public Sub New(syntax As SyntaxNode, eventAccess As BoundExpression, handler As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AddHandlerStatement, syntax, eventAccess, handler, hasErrors OrElse eventAccess.NonNullAndHasErrors() OrElse handler.NonNullAndHasErrors())
Debug.Assert(eventAccess IsNot Nothing, "Field 'eventAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(handler IsNot Nothing, "Field 'handler' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAddHandlerStatement(Me)
End Function
Public Function Update(eventAccess As BoundExpression, handler As BoundExpression) As BoundAddHandlerStatement
If eventAccess IsNot Me.EventAccess OrElse handler IsNot Me.Handler Then
Dim result = New BoundAddHandlerStatement(Me.Syntax, eventAccess, handler, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRemoveHandlerStatement
Inherits BoundAddRemoveHandlerStatement
Public Sub New(syntax As SyntaxNode, eventAccess As BoundExpression, handler As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RemoveHandlerStatement, syntax, eventAccess, handler, hasErrors OrElse eventAccess.NonNullAndHasErrors() OrElse handler.NonNullAndHasErrors())
Debug.Assert(eventAccess IsNot Nothing, "Field 'eventAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(handler IsNot Nothing, "Field 'handler' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRemoveHandlerStatement(Me)
End Function
Public Function Update(eventAccess As BoundExpression, handler As BoundExpression) As BoundRemoveHandlerStatement
If eventAccess IsNot Me.EventAccess OrElse handler IsNot Me.Handler Then
Dim result = New BoundRemoveHandlerStatement(Me.Syntax, eventAccess, handler, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundRaiseEventStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, eventSymbol As EventSymbol, eventInvocation As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.RaiseEventStatement, syntax, hasErrors OrElse eventInvocation.NonNullAndHasErrors())
Debug.Assert(eventSymbol IsNot Nothing, "Field 'eventSymbol' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(eventInvocation IsNot Nothing, "Field 'eventInvocation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._EventSymbol = eventSymbol
Me._EventInvocation = eventInvocation
End Sub
Private ReadOnly _EventSymbol As EventSymbol
Public ReadOnly Property EventSymbol As EventSymbol
Get
Return _EventSymbol
End Get
End Property
Private ReadOnly _EventInvocation As BoundExpression
Public ReadOnly Property EventInvocation As BoundExpression
Get
Return _EventInvocation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitRaiseEventStatement(Me)
End Function
Public Function Update(eventSymbol As EventSymbol, eventInvocation As BoundExpression) As BoundRaiseEventStatement
If eventSymbol IsNot Me.EventSymbol OrElse eventInvocation IsNot Me.EventInvocation Then
Dim result = New BoundRaiseEventStatement(Me.Syntax, eventSymbol, eventInvocation, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUsingStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, resourceList As ImmutableArray(Of BoundLocalDeclarationBase), resourceExpressionOpt As BoundExpression, body As BoundBlock, usingInfo As UsingInfo, locals As ImmutableArray(Of LocalSymbol), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UsingStatement, syntax, hasErrors OrElse resourceList.NonNullAndHasErrors() OrElse resourceExpressionOpt.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(usingInfo IsNot Nothing, "Field 'usingInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ResourceList = resourceList
Me._ResourceExpressionOpt = resourceExpressionOpt
Me._Body = body
Me._UsingInfo = usingInfo
Me._Locals = locals
End Sub
Private ReadOnly _ResourceList As ImmutableArray(Of BoundLocalDeclarationBase)
Public ReadOnly Property ResourceList As ImmutableArray(Of BoundLocalDeclarationBase)
Get
Return _ResourceList
End Get
End Property
Private ReadOnly _ResourceExpressionOpt As BoundExpression
Public ReadOnly Property ResourceExpressionOpt As BoundExpression
Get
Return _ResourceExpressionOpt
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
Private ReadOnly _UsingInfo As UsingInfo
Public ReadOnly Property UsingInfo As UsingInfo
Get
Return _UsingInfo
End Get
End Property
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUsingStatement(Me)
End Function
Public Function Update(resourceList As ImmutableArray(Of BoundLocalDeclarationBase), resourceExpressionOpt As BoundExpression, body As BoundBlock, usingInfo As UsingInfo, locals As ImmutableArray(Of LocalSymbol)) As BoundUsingStatement
If resourceList <> Me.ResourceList OrElse resourceExpressionOpt IsNot Me.ResourceExpressionOpt OrElse body IsNot Me.Body OrElse usingInfo IsNot Me.UsingInfo OrElse locals <> Me.Locals Then
Dim result = New BoundUsingStatement(Me.Syntax, resourceList, resourceExpressionOpt, body, usingInfo, locals, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSyncLockStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, lockExpression As BoundExpression, body As BoundBlock, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SyncLockStatement, syntax, hasErrors OrElse lockExpression.NonNullAndHasErrors() OrElse body.NonNullAndHasErrors())
Debug.Assert(lockExpression IsNot Nothing, "Field 'lockExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._LockExpression = lockExpression
Me._Body = body
End Sub
Private ReadOnly _LockExpression As BoundExpression
Public ReadOnly Property LockExpression As BoundExpression
Get
Return _LockExpression
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSyncLockStatement(Me)
End Function
Public Function Update(lockExpression As BoundExpression, body As BoundBlock) As BoundSyncLockStatement
If lockExpression IsNot Me.LockExpression OrElse body IsNot Me.Body Then
Dim result = New BoundSyncLockStatement(Me.Syntax, lockExpression, body, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlName
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, xmlNamespace As BoundExpression, localName As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlName, syntax, type, hasErrors OrElse xmlNamespace.NonNullAndHasErrors() OrElse localName.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(xmlNamespace IsNot Nothing, "Field 'xmlNamespace' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(localName IsNot Nothing, "Field 'localName' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._XmlNamespace = xmlNamespace
Me._LocalName = localName
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _XmlNamespace As BoundExpression
Public ReadOnly Property XmlNamespace As BoundExpression
Get
Return _XmlNamespace
End Get
End Property
Private ReadOnly _LocalName As BoundExpression
Public ReadOnly Property LocalName As BoundExpression
Get
Return _LocalName
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlName(Me)
End Function
Public Function Update(xmlNamespace As BoundExpression, localName As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlName
If xmlNamespace IsNot Me.XmlNamespace OrElse localName IsNot Me.LocalName OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlName(Me.Syntax, xmlNamespace, localName, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlNamespace
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, xmlNamespace As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlNamespace, syntax, type, hasErrors OrElse xmlNamespace.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(xmlNamespace IsNot Nothing, "Field 'xmlNamespace' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._XmlNamespace = xmlNamespace
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _XmlNamespace As BoundExpression
Public ReadOnly Property XmlNamespace As BoundExpression
Get
Return _XmlNamespace
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlNamespace(Me)
End Function
Public Function Update(xmlNamespace As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlNamespace
If xmlNamespace IsNot Me.XmlNamespace OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlNamespace(Me.Syntax, xmlNamespace, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlDocument
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, declaration As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlDocument, syntax, type, hasErrors OrElse declaration.NonNullAndHasErrors() OrElse childNodes.NonNullAndHasErrors())
Debug.Assert(declaration IsNot Nothing, "Field 'declaration' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (childNodes.IsDefault), "Field 'childNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(rewriterInfo IsNot Nothing, "Field 'rewriterInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Declaration = declaration
Me._ChildNodes = childNodes
Me._RewriterInfo = rewriterInfo
End Sub
Private ReadOnly _Declaration As BoundExpression
Public ReadOnly Property Declaration As BoundExpression
Get
Return _Declaration
End Get
End Property
Private ReadOnly _ChildNodes As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ChildNodes As ImmutableArray(Of BoundExpression)
Get
Return _ChildNodes
End Get
End Property
Private ReadOnly _RewriterInfo As BoundXmlContainerRewriterInfo
Public ReadOnly Property RewriterInfo As BoundXmlContainerRewriterInfo
Get
Return _RewriterInfo
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlDocument(Me)
End Function
Public Function Update(declaration As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol) As BoundXmlDocument
If declaration IsNot Me.Declaration OrElse childNodes <> Me.ChildNodes OrElse rewriterInfo IsNot Me.RewriterInfo OrElse type IsNot Me.Type Then
Dim result = New BoundXmlDocument(Me.Syntax, declaration, childNodes, rewriterInfo, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlDeclaration
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, version As BoundExpression, encoding As BoundExpression, standalone As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlDeclaration, syntax, type, hasErrors OrElse version.NonNullAndHasErrors() OrElse encoding.NonNullAndHasErrors() OrElse standalone.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Version = version
Me._Encoding = encoding
Me._Standalone = standalone
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Version As BoundExpression
Public ReadOnly Property Version As BoundExpression
Get
Return _Version
End Get
End Property
Private ReadOnly _Encoding As BoundExpression
Public ReadOnly Property Encoding As BoundExpression
Get
Return _Encoding
End Get
End Property
Private ReadOnly _Standalone As BoundExpression
Public ReadOnly Property Standalone As BoundExpression
Get
Return _Standalone
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlDeclaration(Me)
End Function
Public Function Update(version As BoundExpression, encoding As BoundExpression, standalone As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlDeclaration
If version IsNot Me.Version OrElse encoding IsNot Me.Encoding OrElse standalone IsNot Me.Standalone OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlDeclaration(Me.Syntax, version, encoding, standalone, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlProcessingInstruction
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, target As BoundExpression, data As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlProcessingInstruction, syntax, type, hasErrors OrElse target.NonNullAndHasErrors() OrElse data.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(target IsNot Nothing, "Field 'target' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(data IsNot Nothing, "Field 'data' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Target = target
Me._Data = data
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Target As BoundExpression
Public ReadOnly Property Target As BoundExpression
Get
Return _Target
End Get
End Property
Private ReadOnly _Data As BoundExpression
Public ReadOnly Property Data As BoundExpression
Get
Return _Data
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlProcessingInstruction(Me)
End Function
Public Function Update(target As BoundExpression, data As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlProcessingInstruction
If target IsNot Me.Target OrElse data IsNot Me.Data OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlProcessingInstruction(Me.Syntax, target, data, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlComment
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, value As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlComment, syntax, type, hasErrors OrElse value.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlComment(Me)
End Function
Public Function Update(value As BoundExpression, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlComment
If value IsNot Me.Value OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlComment(Me.Syntax, value, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlAttribute
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, name As BoundExpression, value As BoundExpression, matchesImport As Boolean, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlAttribute, syntax, type, hasErrors OrElse name.NonNullAndHasErrors() OrElse value.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(name IsNot Nothing, "Field 'name' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Name = name
Me._Value = value
Me._MatchesImport = matchesImport
Me._ObjectCreation = objectCreation
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Name As BoundExpression
Public ReadOnly Property Name As BoundExpression
Get
Return _Name
End Get
End Property
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
Private ReadOnly _MatchesImport As Boolean
Public ReadOnly Property MatchesImport As Boolean
Get
Return _MatchesImport
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlAttribute(Me)
End Function
Public Function Update(name As BoundExpression, value As BoundExpression, matchesImport As Boolean, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlAttribute
If name IsNot Me.Name OrElse value IsNot Me.Value OrElse matchesImport <> Me.MatchesImport OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlAttribute(Me.Syntax, name, value, matchesImport, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlElement
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, argument As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlElement, syntax, type, hasErrors OrElse argument.NonNullAndHasErrors() OrElse childNodes.NonNullAndHasErrors())
Debug.Assert(argument IsNot Nothing, "Field 'argument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (childNodes.IsDefault), "Field 'childNodes' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(rewriterInfo IsNot Nothing, "Field 'rewriterInfo' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Argument = argument
Me._ChildNodes = childNodes
Me._RewriterInfo = rewriterInfo
End Sub
Private ReadOnly _Argument As BoundExpression
Public ReadOnly Property Argument As BoundExpression
Get
Return _Argument
End Get
End Property
Private ReadOnly _ChildNodes As ImmutableArray(Of BoundExpression)
Public ReadOnly Property ChildNodes As ImmutableArray(Of BoundExpression)
Get
Return _ChildNodes
End Get
End Property
Private ReadOnly _RewriterInfo As BoundXmlContainerRewriterInfo
Public ReadOnly Property RewriterInfo As BoundXmlContainerRewriterInfo
Get
Return _RewriterInfo
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlElement(Me)
End Function
Public Function Update(argument As BoundExpression, childNodes As ImmutableArray(Of BoundExpression), rewriterInfo As BoundXmlContainerRewriterInfo, type As TypeSymbol) As BoundXmlElement
If argument IsNot Me.Argument OrElse childNodes <> Me.ChildNodes OrElse rewriterInfo IsNot Me.RewriterInfo OrElse type IsNot Me.Type Then
Dim result = New BoundXmlElement(Me.Syntax, argument, childNodes, rewriterInfo, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlMemberAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, memberAccess As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlMemberAccess, syntax, type, hasErrors OrElse memberAccess.NonNullAndHasErrors())
Debug.Assert(memberAccess IsNot Nothing, "Field 'memberAccess' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._MemberAccess = memberAccess
End Sub
Private ReadOnly _MemberAccess As BoundExpression
Public ReadOnly Property MemberAccess As BoundExpression
Get
Return _MemberAccess
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlMemberAccess(Me)
End Function
Public Function Update(memberAccess As BoundExpression, type As TypeSymbol) As BoundXmlMemberAccess
If memberAccess IsNot Me.MemberAccess OrElse type IsNot Me.Type Then
Dim result = New BoundXmlMemberAccess(Me.Syntax, memberAccess, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlEmbeddedExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlEmbeddedExpression, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlEmbeddedExpression(Me)
End Function
Public Function Update(expression As BoundExpression, type As TypeSymbol) As BoundXmlEmbeddedExpression
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundXmlEmbeddedExpression(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundXmlCData
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, value As BoundLiteral, objectCreation As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.XmlCData, syntax, type, hasErrors OrElse value.NonNullAndHasErrors() OrElse objectCreation.NonNullAndHasErrors())
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(objectCreation IsNot Nothing, "Field 'objectCreation' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Me._ObjectCreation = objectCreation
End Sub
Private ReadOnly _Value As BoundLiteral
Public ReadOnly Property Value As BoundLiteral
Get
Return _Value
End Get
End Property
Private ReadOnly _ObjectCreation As BoundExpression
Public ReadOnly Property ObjectCreation As BoundExpression
Get
Return _ObjectCreation
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitXmlCData(Me)
End Function
Public Function Update(value As BoundLiteral, objectCreation As BoundExpression, type As TypeSymbol) As BoundXmlCData
If value IsNot Me.Value OrElse objectCreation IsNot Me.ObjectCreation OrElse type IsNot Me.Type Then
Dim result = New BoundXmlCData(Me.Syntax, value, objectCreation, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundResumeStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, resumeKind As ResumeStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ResumeStatement, syntax, hasErrors OrElse labelExpressionOpt.NonNullAndHasErrors())
Me._ResumeKind = resumeKind
Me._LabelOpt = labelOpt
Me._LabelExpressionOpt = labelExpressionOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ResumeKind As ResumeStatementKind
Public ReadOnly Property ResumeKind As ResumeStatementKind
Get
Return _ResumeKind
End Get
End Property
Private ReadOnly _LabelOpt As LabelSymbol
Public ReadOnly Property LabelOpt As LabelSymbol
Get
Return _LabelOpt
End Get
End Property
Private ReadOnly _LabelExpressionOpt As BoundExpression
Public ReadOnly Property LabelExpressionOpt As BoundExpression
Get
Return _LabelExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitResumeStatement(Me)
End Function
Public Function Update(resumeKind As ResumeStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression) As BoundResumeStatement
If resumeKind <> Me.ResumeKind OrElse labelOpt IsNot Me.LabelOpt OrElse labelExpressionOpt IsNot Me.LabelExpressionOpt Then
Dim result = New BoundResumeStatement(Me.Syntax, resumeKind, labelOpt, labelExpressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundOnErrorStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, onErrorKind As OnErrorStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.OnErrorStatement, syntax, hasErrors OrElse labelExpressionOpt.NonNullAndHasErrors())
Me._OnErrorKind = onErrorKind
Me._LabelOpt = labelOpt
Me._LabelExpressionOpt = labelExpressionOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _OnErrorKind As OnErrorStatementKind
Public ReadOnly Property OnErrorKind As OnErrorStatementKind
Get
Return _OnErrorKind
End Get
End Property
Private ReadOnly _LabelOpt As LabelSymbol
Public ReadOnly Property LabelOpt As LabelSymbol
Get
Return _LabelOpt
End Get
End Property
Private ReadOnly _LabelExpressionOpt As BoundExpression
Public ReadOnly Property LabelExpressionOpt As BoundExpression
Get
Return _LabelExpressionOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitOnErrorStatement(Me)
End Function
Public Function Update(onErrorKind As OnErrorStatementKind, labelOpt As LabelSymbol, labelExpressionOpt As BoundExpression) As BoundOnErrorStatement
If onErrorKind <> Me.OnErrorKind OrElse labelOpt IsNot Me.LabelOpt OrElse labelExpressionOpt IsNot Me.LabelExpressionOpt Then
Dim result = New BoundOnErrorStatement(Me.Syntax, onErrorKind, labelOpt, labelExpressionOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionHandlingStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, containsOnError As Boolean, containsResume As Boolean, resumeWithoutLabelOpt As StatementSyntax, trackLineNumber As Boolean, body As BoundBlock, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionHandlingStatement, syntax, hasErrors OrElse body.NonNullAndHasErrors())
Debug.Assert(body IsNot Nothing, "Field 'body' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ContainsOnError = containsOnError
Me._ContainsResume = containsResume
Me._ResumeWithoutLabelOpt = resumeWithoutLabelOpt
Me._TrackLineNumber = trackLineNumber
Me._Body = body
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ContainsOnError As Boolean
Public ReadOnly Property ContainsOnError As Boolean
Get
Return _ContainsOnError
End Get
End Property
Private ReadOnly _ContainsResume As Boolean
Public ReadOnly Property ContainsResume As Boolean
Get
Return _ContainsResume
End Get
End Property
Private ReadOnly _ResumeWithoutLabelOpt As StatementSyntax
Public ReadOnly Property ResumeWithoutLabelOpt As StatementSyntax
Get
Return _ResumeWithoutLabelOpt
End Get
End Property
Private ReadOnly _TrackLineNumber As Boolean
Public ReadOnly Property TrackLineNumber As Boolean
Get
Return _TrackLineNumber
End Get
End Property
Private ReadOnly _Body As BoundBlock
Public ReadOnly Property Body As BoundBlock
Get
Return _Body
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionHandlingStatement(Me)
End Function
Public Function Update(containsOnError As Boolean, containsResume As Boolean, resumeWithoutLabelOpt As StatementSyntax, trackLineNumber As Boolean, body As BoundBlock) As BoundUnstructuredExceptionHandlingStatement
If containsOnError <> Me.ContainsOnError OrElse containsResume <> Me.ContainsResume OrElse resumeWithoutLabelOpt IsNot Me.ResumeWithoutLabelOpt OrElse trackLineNumber <> Me.TrackLineNumber OrElse body IsNot Me.Body Then
Dim result = New BoundUnstructuredExceptionHandlingStatement(Me.Syntax, containsOnError, containsResume, resumeWithoutLabelOpt, trackLineNumber, body, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionHandlingCatchFilter
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, activeHandlerLocal As BoundLocal, resumeTargetLocal As BoundLocal, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionHandlingCatchFilter, syntax, type, hasErrors OrElse activeHandlerLocal.NonNullAndHasErrors() OrElse resumeTargetLocal.NonNullAndHasErrors())
Debug.Assert(activeHandlerLocal IsNot Nothing, "Field 'activeHandlerLocal' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(resumeTargetLocal IsNot Nothing, "Field 'resumeTargetLocal' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ActiveHandlerLocal = activeHandlerLocal
Me._ResumeTargetLocal = resumeTargetLocal
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ActiveHandlerLocal As BoundLocal
Public ReadOnly Property ActiveHandlerLocal As BoundLocal
Get
Return _ActiveHandlerLocal
End Get
End Property
Private ReadOnly _ResumeTargetLocal As BoundLocal
Public ReadOnly Property ResumeTargetLocal As BoundLocal
Get
Return _ResumeTargetLocal
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionHandlingCatchFilter(Me)
End Function
Public Function Update(activeHandlerLocal As BoundLocal, resumeTargetLocal As BoundLocal, type As TypeSymbol) As BoundUnstructuredExceptionHandlingCatchFilter
If activeHandlerLocal IsNot Me.ActiveHandlerLocal OrElse resumeTargetLocal IsNot Me.ResumeTargetLocal OrElse type IsNot Me.Type Then
Dim result = New BoundUnstructuredExceptionHandlingCatchFilter(Me.Syntax, activeHandlerLocal, resumeTargetLocal, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionOnErrorSwitch
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, value As BoundExpression, jumps As ImmutableArray(Of BoundGotoStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionOnErrorSwitch, syntax, hasErrors OrElse value.NonNullAndHasErrors() OrElse jumps.NonNullAndHasErrors())
Debug.Assert(value IsNot Nothing, "Field 'value' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (jumps.IsDefault), "Field 'jumps' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Value = value
Me._Jumps = jumps
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Value As BoundExpression
Public ReadOnly Property Value As BoundExpression
Get
Return _Value
End Get
End Property
Private ReadOnly _Jumps As ImmutableArray(Of BoundGotoStatement)
Public ReadOnly Property Jumps As ImmutableArray(Of BoundGotoStatement)
Get
Return _Jumps
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionOnErrorSwitch(Me)
End Function
Public Function Update(value As BoundExpression, jumps As ImmutableArray(Of BoundGotoStatement)) As BoundUnstructuredExceptionOnErrorSwitch
If value IsNot Me.Value OrElse jumps <> Me.Jumps Then
Dim result = New BoundUnstructuredExceptionOnErrorSwitch(Me.Syntax, value, jumps, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundUnstructuredExceptionResumeSwitch
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, resumeTargetTemporary As BoundLocal, resumeLabel As BoundLabelStatement, resumeNextLabel As BoundLabelStatement, jumps As ImmutableArray(Of BoundGotoStatement), Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.UnstructuredExceptionResumeSwitch, syntax, hasErrors OrElse resumeTargetTemporary.NonNullAndHasErrors() OrElse resumeLabel.NonNullAndHasErrors() OrElse resumeNextLabel.NonNullAndHasErrors() OrElse jumps.NonNullAndHasErrors())
Debug.Assert(resumeTargetTemporary IsNot Nothing, "Field 'resumeTargetTemporary' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(resumeLabel IsNot Nothing, "Field 'resumeLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(resumeNextLabel IsNot Nothing, "Field 'resumeNextLabel' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (jumps.IsDefault), "Field 'jumps' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ResumeTargetTemporary = resumeTargetTemporary
Me._ResumeLabel = resumeLabel
Me._ResumeNextLabel = resumeNextLabel
Me._Jumps = jumps
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ResumeTargetTemporary As BoundLocal
Public ReadOnly Property ResumeTargetTemporary As BoundLocal
Get
Return _ResumeTargetTemporary
End Get
End Property
Private ReadOnly _ResumeLabel As BoundLabelStatement
Public ReadOnly Property ResumeLabel As BoundLabelStatement
Get
Return _ResumeLabel
End Get
End Property
Private ReadOnly _ResumeNextLabel As BoundLabelStatement
Public ReadOnly Property ResumeNextLabel As BoundLabelStatement
Get
Return _ResumeNextLabel
End Get
End Property
Private ReadOnly _Jumps As ImmutableArray(Of BoundGotoStatement)
Public ReadOnly Property Jumps As ImmutableArray(Of BoundGotoStatement)
Get
Return _Jumps
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitUnstructuredExceptionResumeSwitch(Me)
End Function
Public Function Update(resumeTargetTemporary As BoundLocal, resumeLabel As BoundLabelStatement, resumeNextLabel As BoundLabelStatement, jumps As ImmutableArray(Of BoundGotoStatement)) As BoundUnstructuredExceptionResumeSwitch
If resumeTargetTemporary IsNot Me.ResumeTargetTemporary OrElse resumeLabel IsNot Me.ResumeLabel OrElse resumeNextLabel IsNot Me.ResumeNextLabel OrElse jumps <> Me.Jumps Then
Dim result = New BoundUnstructuredExceptionResumeSwitch(Me.Syntax, resumeTargetTemporary, resumeLabel, resumeNextLabel, jumps, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundAwaitOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, operand As BoundExpression, awaitableInstancePlaceholder As BoundRValuePlaceholder, getAwaiter As BoundExpression, awaiterInstancePlaceholder As BoundLValuePlaceholder, isCompleted As BoundExpression, getResult As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.AwaitOperator, syntax, type, hasErrors OrElse operand.NonNullAndHasErrors() OrElse awaitableInstancePlaceholder.NonNullAndHasErrors() OrElse getAwaiter.NonNullAndHasErrors() OrElse awaiterInstancePlaceholder.NonNullAndHasErrors() OrElse isCompleted.NonNullAndHasErrors() OrElse getResult.NonNullAndHasErrors())
Debug.Assert(operand IsNot Nothing, "Field 'operand' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(awaitableInstancePlaceholder IsNot Nothing, "Field 'awaitableInstancePlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(getAwaiter IsNot Nothing, "Field 'getAwaiter' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(awaiterInstancePlaceholder IsNot Nothing, "Field 'awaiterInstancePlaceholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(isCompleted IsNot Nothing, "Field 'isCompleted' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(getResult IsNot Nothing, "Field 'getResult' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Operand = operand
Me._AwaitableInstancePlaceholder = awaitableInstancePlaceholder
Me._GetAwaiter = getAwaiter
Me._AwaiterInstancePlaceholder = awaiterInstancePlaceholder
Me._IsCompleted = isCompleted
Me._GetResult = getResult
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Operand As BoundExpression
Public ReadOnly Property Operand As BoundExpression
Get
Return _Operand
End Get
End Property
Private ReadOnly _AwaitableInstancePlaceholder As BoundRValuePlaceholder
Public ReadOnly Property AwaitableInstancePlaceholder As BoundRValuePlaceholder
Get
Return _AwaitableInstancePlaceholder
End Get
End Property
Private ReadOnly _GetAwaiter As BoundExpression
Public ReadOnly Property GetAwaiter As BoundExpression
Get
Return _GetAwaiter
End Get
End Property
Private ReadOnly _AwaiterInstancePlaceholder As BoundLValuePlaceholder
Public ReadOnly Property AwaiterInstancePlaceholder As BoundLValuePlaceholder
Get
Return _AwaiterInstancePlaceholder
End Get
End Property
Private ReadOnly _IsCompleted As BoundExpression
Public ReadOnly Property IsCompleted As BoundExpression
Get
Return _IsCompleted
End Get
End Property
Private ReadOnly _GetResult As BoundExpression
Public ReadOnly Property GetResult As BoundExpression
Get
Return _GetResult
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitAwaitOperator(Me)
End Function
Public Function Update(operand As BoundExpression, awaitableInstancePlaceholder As BoundRValuePlaceholder, getAwaiter As BoundExpression, awaiterInstancePlaceholder As BoundLValuePlaceholder, isCompleted As BoundExpression, getResult As BoundExpression, type As TypeSymbol) As BoundAwaitOperator
If operand IsNot Me.Operand OrElse awaitableInstancePlaceholder IsNot Me.AwaitableInstancePlaceholder OrElse getAwaiter IsNot Me.GetAwaiter OrElse awaiterInstancePlaceholder IsNot Me.AwaiterInstancePlaceholder OrElse isCompleted IsNot Me.IsCompleted OrElse getResult IsNot Me.GetResult OrElse type IsNot Me.Type Then
Dim result = New BoundAwaitOperator(Me.Syntax, operand, awaitableInstancePlaceholder, getAwaiter, awaiterInstancePlaceholder, isCompleted, getResult, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundSpillSequence
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, locals As ImmutableArray(Of LocalSymbol), spillFields As ImmutableArray(Of FieldSymbol), statements As ImmutableArray(Of BoundStatement), valueOpt As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.SpillSequence, syntax, type, hasErrors OrElse statements.NonNullAndHasErrors() OrElse valueOpt.NonNullAndHasErrors())
Debug.Assert(Not (locals.IsDefault), "Field 'locals' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (spillFields.IsDefault), "Field 'spillFields' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(Not (statements.IsDefault), "Field 'statements' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Locals = locals
Me._SpillFields = spillFields
Me._Statements = statements
Me._ValueOpt = valueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Locals As ImmutableArray(Of LocalSymbol)
Public ReadOnly Property Locals As ImmutableArray(Of LocalSymbol)
Get
Return _Locals
End Get
End Property
Private ReadOnly _SpillFields As ImmutableArray(Of FieldSymbol)
Public ReadOnly Property SpillFields As ImmutableArray(Of FieldSymbol)
Get
Return _SpillFields
End Get
End Property
Private ReadOnly _Statements As ImmutableArray(Of BoundStatement)
Public ReadOnly Property Statements As ImmutableArray(Of BoundStatement)
Get
Return _Statements
End Get
End Property
Private ReadOnly _ValueOpt As BoundExpression
Public ReadOnly Property ValueOpt As BoundExpression
Get
Return _ValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitSpillSequence(Me)
End Function
Public Function Update(locals As ImmutableArray(Of LocalSymbol), spillFields As ImmutableArray(Of FieldSymbol), statements As ImmutableArray(Of BoundStatement), valueOpt As BoundExpression, type As TypeSymbol) As BoundSpillSequence
If locals <> Me.Locals OrElse spillFields <> Me.SpillFields OrElse statements <> Me.Statements OrElse valueOpt IsNot Me.ValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundSpillSequence(Me.Syntax, locals, spillFields, statements, valueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundStopStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyBase.New(BoundKind.StopStatement, syntax, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode)
MyBase.New(BoundKind.StopStatement, syntax)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitStopStatement(Me)
End Function
End Class
Partial Friend NotInheritable Class BoundEndStatement
Inherits BoundStatement
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyBase.New(BoundKind.EndStatement, syntax, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode)
MyBase.New(BoundKind.EndStatement, syntax)
End Sub
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitEndStatement(Me)
End Function
End Class
Partial Friend NotInheritable Class BoundMidResult
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, original As BoundExpression, start As BoundExpression, lengthOpt As BoundExpression, source As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.MidResult, syntax, type, hasErrors OrElse original.NonNullAndHasErrors() OrElse start.NonNullAndHasErrors() OrElse lengthOpt.NonNullAndHasErrors() OrElse source.NonNullAndHasErrors())
Debug.Assert(original IsNot Nothing, "Field 'original' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(start IsNot Nothing, "Field 'start' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(source IsNot Nothing, "Field 'source' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Original = original
Me._Start = start
Me._LengthOpt = lengthOpt
Me._Source = source
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Original As BoundExpression
Public ReadOnly Property Original As BoundExpression
Get
Return _Original
End Get
End Property
Private ReadOnly _Start As BoundExpression
Public ReadOnly Property Start As BoundExpression
Get
Return _Start
End Get
End Property
Private ReadOnly _LengthOpt As BoundExpression
Public ReadOnly Property LengthOpt As BoundExpression
Get
Return _LengthOpt
End Get
End Property
Private ReadOnly _Source As BoundExpression
Public ReadOnly Property Source As BoundExpression
Get
Return _Source
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitMidResult(Me)
End Function
Public Function Update(original As BoundExpression, start As BoundExpression, lengthOpt As BoundExpression, source As BoundExpression, type As TypeSymbol) As BoundMidResult
If original IsNot Me.Original OrElse start IsNot Me.Start OrElse lengthOpt IsNot Me.LengthOpt OrElse source IsNot Me.Source OrElse type IsNot Me.Type Then
Dim result = New BoundMidResult(Me.Syntax, original, start, lengthOpt, source, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConditionalAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiver As BoundExpression, placeholder As BoundRValuePlaceholder, accessExpression As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ConditionalAccess, syntax, type, hasErrors OrElse receiver.NonNullAndHasErrors() OrElse placeholder.NonNullAndHasErrors() OrElse accessExpression.NonNullAndHasErrors())
Debug.Assert(receiver IsNot Nothing, "Field 'receiver' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(placeholder IsNot Nothing, "Field 'placeholder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(accessExpression IsNot Nothing, "Field 'accessExpression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Receiver = receiver
Me._Placeholder = placeholder
Me._AccessExpression = accessExpression
End Sub
Private ReadOnly _Receiver As BoundExpression
Public ReadOnly Property Receiver As BoundExpression
Get
Return _Receiver
End Get
End Property
Private ReadOnly _Placeholder As BoundRValuePlaceholder
Public ReadOnly Property Placeholder As BoundRValuePlaceholder
Get
Return _Placeholder
End Get
End Property
Private ReadOnly _AccessExpression As BoundExpression
Public ReadOnly Property AccessExpression As BoundExpression
Get
Return _AccessExpression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConditionalAccess(Me)
End Function
Public Function Update(receiver As BoundExpression, placeholder As BoundRValuePlaceholder, accessExpression As BoundExpression, type As TypeSymbol) As BoundConditionalAccess
If receiver IsNot Me.Receiver OrElse placeholder IsNot Me.Placeholder OrElse accessExpression IsNot Me.AccessExpression OrElse type IsNot Me.Type Then
Dim result = New BoundConditionalAccess(Me.Syntax, receiver, placeholder, accessExpression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundConditionalAccessReceiverPlaceholder
Inherits BoundRValuePlaceholderBase
Public Sub New(syntax As SyntaxNode, placeholderId As Integer, type As TypeSymbol, hasErrors As Boolean)
MyBase.New(BoundKind.ConditionalAccessReceiverPlaceholder, syntax, type, hasErrors)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PlaceholderId = placeholderId
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Public Sub New(syntax As SyntaxNode, placeholderId As Integer, type As TypeSymbol)
MyBase.New(BoundKind.ConditionalAccessReceiverPlaceholder, syntax, type)
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._PlaceholderId = placeholderId
Validate()
End Sub
Private ReadOnly _PlaceholderId As Integer
Public ReadOnly Property PlaceholderId As Integer
Get
Return _PlaceholderId
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitConditionalAccessReceiverPlaceholder(Me)
End Function
Public Function Update(placeholderId As Integer, type As TypeSymbol) As BoundConditionalAccessReceiverPlaceholder
If placeholderId <> Me.PlaceholderId OrElse type IsNot Me.Type Then
Dim result = New BoundConditionalAccessReceiverPlaceholder(Me.Syntax, placeholderId, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundLoweredConditionalAccess
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, receiverOrCondition As BoundExpression, captureReceiver As Boolean, placeholderId As Integer, whenNotNull As BoundExpression, whenNullOpt As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.LoweredConditionalAccess, syntax, type, hasErrors OrElse receiverOrCondition.NonNullAndHasErrors() OrElse whenNotNull.NonNullAndHasErrors() OrElse whenNullOpt.NonNullAndHasErrors())
Debug.Assert(receiverOrCondition IsNot Nothing, "Field 'receiverOrCondition' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(whenNotNull IsNot Nothing, "Field 'whenNotNull' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ReceiverOrCondition = receiverOrCondition
Me._CaptureReceiver = captureReceiver
Me._PlaceholderId = placeholderId
Me._WhenNotNull = whenNotNull
Me._WhenNullOpt = whenNullOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ReceiverOrCondition As BoundExpression
Public ReadOnly Property ReceiverOrCondition As BoundExpression
Get
Return _ReceiverOrCondition
End Get
End Property
Private ReadOnly _CaptureReceiver As Boolean
Public ReadOnly Property CaptureReceiver As Boolean
Get
Return _CaptureReceiver
End Get
End Property
Private ReadOnly _PlaceholderId As Integer
Public ReadOnly Property PlaceholderId As Integer
Get
Return _PlaceholderId
End Get
End Property
Private ReadOnly _WhenNotNull As BoundExpression
Public ReadOnly Property WhenNotNull As BoundExpression
Get
Return _WhenNotNull
End Get
End Property
Private ReadOnly _WhenNullOpt As BoundExpression
Public ReadOnly Property WhenNullOpt As BoundExpression
Get
Return _WhenNullOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitLoweredConditionalAccess(Me)
End Function
Public Function Update(receiverOrCondition As BoundExpression, captureReceiver As Boolean, placeholderId As Integer, whenNotNull As BoundExpression, whenNullOpt As BoundExpression, type As TypeSymbol) As BoundLoweredConditionalAccess
If receiverOrCondition IsNot Me.ReceiverOrCondition OrElse captureReceiver <> Me.CaptureReceiver OrElse placeholderId <> Me.PlaceholderId OrElse whenNotNull IsNot Me.WhenNotNull OrElse whenNullOpt IsNot Me.WhenNullOpt OrElse type IsNot Me.Type Then
Dim result = New BoundLoweredConditionalAccess(Me.Syntax, receiverOrCondition, captureReceiver, placeholderId, whenNotNull, whenNullOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundComplexConditionalAccessReceiver
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, valueTypeReceiver As BoundExpression, referenceTypeReceiver As BoundExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.ComplexConditionalAccessReceiver, syntax, type, hasErrors OrElse valueTypeReceiver.NonNullAndHasErrors() OrElse referenceTypeReceiver.NonNullAndHasErrors())
Debug.Assert(valueTypeReceiver IsNot Nothing, "Field 'valueTypeReceiver' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(referenceTypeReceiver IsNot Nothing, "Field 'referenceTypeReceiver' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._ValueTypeReceiver = valueTypeReceiver
Me._ReferenceTypeReceiver = referenceTypeReceiver
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _ValueTypeReceiver As BoundExpression
Public ReadOnly Property ValueTypeReceiver As BoundExpression
Get
Return _ValueTypeReceiver
End Get
End Property
Private ReadOnly _ReferenceTypeReceiver As BoundExpression
Public ReadOnly Property ReferenceTypeReceiver As BoundExpression
Get
Return _ReferenceTypeReceiver
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitComplexConditionalAccessReceiver(Me)
End Function
Public Function Update(valueTypeReceiver As BoundExpression, referenceTypeReceiver As BoundExpression, type As TypeSymbol) As BoundComplexConditionalAccessReceiver
If valueTypeReceiver IsNot Me.ValueTypeReceiver OrElse referenceTypeReceiver IsNot Me.ReferenceTypeReceiver OrElse type IsNot Me.Type Then
Dim result = New BoundComplexConditionalAccessReceiver(Me.Syntax, valueTypeReceiver, referenceTypeReceiver, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundNameOfOperator
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, argument As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.NameOfOperator, syntax, type, hasErrors OrElse argument.NonNullAndHasErrors())
Debug.Assert(argument IsNot Nothing, "Field 'argument' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Argument = argument
Me._ConstantValueOpt = constantValueOpt
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Argument As BoundExpression
Public ReadOnly Property Argument As BoundExpression
Get
Return _Argument
End Get
End Property
Private ReadOnly _ConstantValueOpt As ConstantValue
Public Overrides ReadOnly Property ConstantValueOpt As ConstantValue
Get
Return _ConstantValueOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitNameOfOperator(Me)
End Function
Public Function Update(argument As BoundExpression, constantValueOpt As ConstantValue, type As TypeSymbol) As BoundNameOfOperator
If argument IsNot Me.Argument OrElse constantValueOpt IsNot Me.ConstantValueOpt OrElse type IsNot Me.Type Then
Dim result = New BoundNameOfOperator(Me.Syntax, argument, constantValueOpt, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundTypeAsValueExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, expression As BoundTypeExpression, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.TypeAsValueExpression, syntax, type, hasErrors OrElse expression.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Expression As BoundTypeExpression
Public ReadOnly Property Expression As BoundTypeExpression
Get
Return _Expression
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitTypeAsValueExpression(Me)
End Function
Public Function Update(expression As BoundTypeExpression, type As TypeSymbol) As BoundTypeAsValueExpression
If expression IsNot Me.Expression OrElse type IsNot Me.Type Then
Dim result = New BoundTypeAsValueExpression(Me.Syntax, expression, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundInterpolatedStringExpression
Inherits BoundExpression
Public Sub New(syntax As SyntaxNode, contents As ImmutableArray(Of BoundNode), binder As Binder, type As TypeSymbol, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.InterpolatedStringExpression, syntax, type, hasErrors OrElse contents.NonNullAndHasErrors())
Debug.Assert(Not (contents.IsDefault), "Field 'contents' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(binder IsNot Nothing, "Field 'binder' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Debug.Assert(type IsNot Nothing, "Field 'type' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Contents = contents
Me._Binder = binder
Validate()
End Sub
Private Partial Sub Validate()
End Sub
Private ReadOnly _Contents As ImmutableArray(Of BoundNode)
Public ReadOnly Property Contents As ImmutableArray(Of BoundNode)
Get
Return _Contents
End Get
End Property
Private ReadOnly _Binder As Binder
Public ReadOnly Property Binder As Binder
Get
Return _Binder
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInterpolatedStringExpression(Me)
End Function
Public Function Update(contents As ImmutableArray(Of BoundNode), binder As Binder, type As TypeSymbol) As BoundInterpolatedStringExpression
If contents <> Me.Contents OrElse binder IsNot Me.Binder OrElse type IsNot Me.Type Then
Dim result = New BoundInterpolatedStringExpression(Me.Syntax, contents, binder, type, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Partial Friend NotInheritable Class BoundInterpolation
Inherits BoundNode
Public Sub New(syntax As SyntaxNode, expression As BoundExpression, alignmentOpt As BoundExpression, formatStringOpt As BoundLiteral, Optional hasErrors As Boolean = False)
MyBase.New(BoundKind.Interpolation, syntax, hasErrors OrElse expression.NonNullAndHasErrors() OrElse alignmentOpt.NonNullAndHasErrors() OrElse formatStringOpt.NonNullAndHasErrors())
Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)")
Me._Expression = expression
Me._AlignmentOpt = alignmentOpt
Me._FormatStringOpt = formatStringOpt
End Sub
Private ReadOnly _Expression As BoundExpression
Public ReadOnly Property Expression As BoundExpression
Get
Return _Expression
End Get
End Property
Private ReadOnly _AlignmentOpt As BoundExpression
Public ReadOnly Property AlignmentOpt As BoundExpression
Get
Return _AlignmentOpt
End Get
End Property
Private ReadOnly _FormatStringOpt As BoundLiteral
Public ReadOnly Property FormatStringOpt As BoundLiteral
Get
Return _FormatStringOpt
End Get
End Property
<DebuggerStepThrough>
Public Overrides Function Accept(visitor as BoundTreeVisitor) As BoundNode
Return visitor.VisitInterpolation(Me)
End Function
Public Function Update(expression As BoundExpression, alignmentOpt As BoundExpression, formatStringOpt As BoundLiteral) As BoundInterpolation
If expression IsNot Me.Expression OrElse alignmentOpt IsNot Me.AlignmentOpt OrElse formatStringOpt IsNot Me.FormatStringOpt Then
Dim result = New BoundInterpolation(Me.Syntax, expression, alignmentOpt, formatStringOpt, Me.HasErrors)
result.CopyAttributes(Me)
Return result
End If
Return Me
End Function
End Class
Friend MustInherit Partial Class BoundTreeVisitor(Of A, R)
<MethodImpl(MethodImplOptions.NoInlining), DebuggerStepThrough>
Friend Function VisitInternal(node As BoundNode, arg As A) As R
Select Case node.Kind
Case BoundKind.TypeArguments
Return VisitTypeArguments(CType(node, BoundTypeArguments), arg)
Case BoundKind.OmittedArgument
Return VisitOmittedArgument(CType(node, BoundOmittedArgument), arg)
Case BoundKind.LValueToRValueWrapper
Return VisitLValueToRValueWrapper(CType(node, BoundLValueToRValueWrapper), arg)
Case BoundKind.WithLValueExpressionPlaceholder
Return VisitWithLValueExpressionPlaceholder(CType(node, BoundWithLValueExpressionPlaceholder), arg)
Case BoundKind.WithRValueExpressionPlaceholder
Return VisitWithRValueExpressionPlaceholder(CType(node, BoundWithRValueExpressionPlaceholder), arg)
Case BoundKind.RValuePlaceholder
Return VisitRValuePlaceholder(CType(node, BoundRValuePlaceholder), arg)
Case BoundKind.LValuePlaceholder
Return VisitLValuePlaceholder(CType(node, BoundLValuePlaceholder), arg)
Case BoundKind.Dup
Return VisitDup(CType(node, BoundDup), arg)
Case BoundKind.BadExpression
Return VisitBadExpression(CType(node, BoundBadExpression), arg)
Case BoundKind.BadStatement
Return VisitBadStatement(CType(node, BoundBadStatement), arg)
Case BoundKind.Parenthesized
Return VisitParenthesized(CType(node, BoundParenthesized), arg)
Case BoundKind.BadVariable
Return VisitBadVariable(CType(node, BoundBadVariable), arg)
Case BoundKind.ArrayAccess
Return VisitArrayAccess(CType(node, BoundArrayAccess), arg)
Case BoundKind.ArrayLength
Return VisitArrayLength(CType(node, BoundArrayLength), arg)
Case BoundKind.[GetType]
Return VisitGetType(CType(node, BoundGetType), arg)
Case BoundKind.FieldInfo
Return VisitFieldInfo(CType(node, BoundFieldInfo), arg)
Case BoundKind.MethodInfo
Return VisitMethodInfo(CType(node, BoundMethodInfo), arg)
Case BoundKind.TypeExpression
Return VisitTypeExpression(CType(node, BoundTypeExpression), arg)
Case BoundKind.TypeOrValueExpression
Return VisitTypeOrValueExpression(CType(node, BoundTypeOrValueExpression), arg)
Case BoundKind.NamespaceExpression
Return VisitNamespaceExpression(CType(node, BoundNamespaceExpression), arg)
Case BoundKind.MethodDefIndex
Return VisitMethodDefIndex(CType(node, BoundMethodDefIndex), arg)
Case BoundKind.MaximumMethodDefIndex
Return VisitMaximumMethodDefIndex(CType(node, BoundMaximumMethodDefIndex), arg)
Case BoundKind.InstrumentationPayloadRoot
Return VisitInstrumentationPayloadRoot(CType(node, BoundInstrumentationPayloadRoot), arg)
Case BoundKind.ModuleVersionId
Return VisitModuleVersionId(CType(node, BoundModuleVersionId), arg)
Case BoundKind.ModuleVersionIdString
Return VisitModuleVersionIdString(CType(node, BoundModuleVersionIdString), arg)
Case BoundKind.SourceDocumentIndex
Return VisitSourceDocumentIndex(CType(node, BoundSourceDocumentIndex), arg)
Case BoundKind.UnaryOperator
Return VisitUnaryOperator(CType(node, BoundUnaryOperator), arg)
Case BoundKind.UserDefinedUnaryOperator
Return VisitUserDefinedUnaryOperator(CType(node, BoundUserDefinedUnaryOperator), arg)
Case BoundKind.NullableIsTrueOperator
Return VisitNullableIsTrueOperator(CType(node, BoundNullableIsTrueOperator), arg)
Case BoundKind.BinaryOperator
Return VisitBinaryOperator(CType(node, BoundBinaryOperator), arg)
Case BoundKind.UserDefinedBinaryOperator
Return VisitUserDefinedBinaryOperator(CType(node, BoundUserDefinedBinaryOperator), arg)
Case BoundKind.UserDefinedShortCircuitingOperator
Return VisitUserDefinedShortCircuitingOperator(CType(node, BoundUserDefinedShortCircuitingOperator), arg)
Case BoundKind.CompoundAssignmentTargetPlaceholder
Return VisitCompoundAssignmentTargetPlaceholder(CType(node, BoundCompoundAssignmentTargetPlaceholder), arg)
Case BoundKind.AssignmentOperator
Return VisitAssignmentOperator(CType(node, BoundAssignmentOperator), arg)
Case BoundKind.ReferenceAssignment
Return VisitReferenceAssignment(CType(node, BoundReferenceAssignment), arg)
Case BoundKind.AddressOfOperator
Return VisitAddressOfOperator(CType(node, BoundAddressOfOperator), arg)
Case BoundKind.TernaryConditionalExpression
Return VisitTernaryConditionalExpression(CType(node, BoundTernaryConditionalExpression), arg)
Case BoundKind.BinaryConditionalExpression
Return VisitBinaryConditionalExpression(CType(node, BoundBinaryConditionalExpression), arg)
Case BoundKind.Conversion
Return VisitConversion(CType(node, BoundConversion), arg)
Case BoundKind.RelaxationLambda
Return VisitRelaxationLambda(CType(node, BoundRelaxationLambda), arg)
Case BoundKind.ConvertedTupleElements
Return VisitConvertedTupleElements(CType(node, BoundConvertedTupleElements), arg)
Case BoundKind.UserDefinedConversion
Return VisitUserDefinedConversion(CType(node, BoundUserDefinedConversion), arg)
Case BoundKind.[DirectCast]
Return VisitDirectCast(CType(node, BoundDirectCast), arg)
Case BoundKind.[TryCast]
Return VisitTryCast(CType(node, BoundTryCast), arg)
Case BoundKind.[TypeOf]
Return VisitTypeOf(CType(node, BoundTypeOf), arg)
Case BoundKind.SequencePoint
Return VisitSequencePoint(CType(node, BoundSequencePoint), arg)
Case BoundKind.SequencePointExpression
Return VisitSequencePointExpression(CType(node, BoundSequencePointExpression), arg)
Case BoundKind.SequencePointWithSpan
Return VisitSequencePointWithSpan(CType(node, BoundSequencePointWithSpan), arg)
Case BoundKind.NoOpStatement
Return VisitNoOpStatement(CType(node, BoundNoOpStatement), arg)
Case BoundKind.MethodGroup
Return VisitMethodGroup(CType(node, BoundMethodGroup), arg)
Case BoundKind.PropertyGroup
Return VisitPropertyGroup(CType(node, BoundPropertyGroup), arg)
Case BoundKind.ReturnStatement
Return VisitReturnStatement(CType(node, BoundReturnStatement), arg)
Case BoundKind.YieldStatement
Return VisitYieldStatement(CType(node, BoundYieldStatement), arg)
Case BoundKind.ThrowStatement
Return VisitThrowStatement(CType(node, BoundThrowStatement), arg)
Case BoundKind.RedimStatement
Return VisitRedimStatement(CType(node, BoundRedimStatement), arg)
Case BoundKind.RedimClause
Return VisitRedimClause(CType(node, BoundRedimClause), arg)
Case BoundKind.EraseStatement
Return VisitEraseStatement(CType(node, BoundEraseStatement), arg)
Case BoundKind.[Call]
Return VisitCall(CType(node, BoundCall), arg)
Case BoundKind.Attribute
Return VisitAttribute(CType(node, BoundAttribute), arg)
Case BoundKind.LateMemberAccess
Return VisitLateMemberAccess(CType(node, BoundLateMemberAccess), arg)
Case BoundKind.LateInvocation
Return VisitLateInvocation(CType(node, BoundLateInvocation), arg)
Case BoundKind.LateAddressOfOperator
Return VisitLateAddressOfOperator(CType(node, BoundLateAddressOfOperator), arg)
Case BoundKind.TupleLiteral
Return VisitTupleLiteral(CType(node, BoundTupleLiteral), arg)
Case BoundKind.ConvertedTupleLiteral
Return VisitConvertedTupleLiteral(CType(node, BoundConvertedTupleLiteral), arg)
Case BoundKind.ObjectCreationExpression
Return VisitObjectCreationExpression(CType(node, BoundObjectCreationExpression), arg)
Case BoundKind.NoPiaObjectCreationExpression
Return VisitNoPiaObjectCreationExpression(CType(node, BoundNoPiaObjectCreationExpression), arg)
Case BoundKind.AnonymousTypeCreationExpression
Return VisitAnonymousTypeCreationExpression(CType(node, BoundAnonymousTypeCreationExpression), arg)
Case BoundKind.AnonymousTypePropertyAccess
Return VisitAnonymousTypePropertyAccess(CType(node, BoundAnonymousTypePropertyAccess), arg)
Case BoundKind.AnonymousTypeFieldInitializer
Return VisitAnonymousTypeFieldInitializer(CType(node, BoundAnonymousTypeFieldInitializer), arg)
Case BoundKind.ObjectInitializerExpression
Return VisitObjectInitializerExpression(CType(node, BoundObjectInitializerExpression), arg)
Case BoundKind.CollectionInitializerExpression
Return VisitCollectionInitializerExpression(CType(node, BoundCollectionInitializerExpression), arg)
Case BoundKind.NewT
Return VisitNewT(CType(node, BoundNewT), arg)
Case BoundKind.DelegateCreationExpression
Return VisitDelegateCreationExpression(CType(node, BoundDelegateCreationExpression), arg)
Case BoundKind.ArrayCreation
Return VisitArrayCreation(CType(node, BoundArrayCreation), arg)
Case BoundKind.ArrayLiteral
Return VisitArrayLiteral(CType(node, BoundArrayLiteral), arg)
Case BoundKind.ArrayInitialization
Return VisitArrayInitialization(CType(node, BoundArrayInitialization), arg)
Case BoundKind.FieldAccess
Return VisitFieldAccess(CType(node, BoundFieldAccess), arg)
Case BoundKind.PropertyAccess
Return VisitPropertyAccess(CType(node, BoundPropertyAccess), arg)
Case BoundKind.EventAccess
Return VisitEventAccess(CType(node, BoundEventAccess), arg)
Case BoundKind.Block
Return VisitBlock(CType(node, BoundBlock), arg)
Case BoundKind.StateMachineScope
Return VisitStateMachineScope(CType(node, BoundStateMachineScope), arg)
Case BoundKind.LocalDeclaration
Return VisitLocalDeclaration(CType(node, BoundLocalDeclaration), arg)
Case BoundKind.AsNewLocalDeclarations
Return VisitAsNewLocalDeclarations(CType(node, BoundAsNewLocalDeclarations), arg)
Case BoundKind.DimStatement
Return VisitDimStatement(CType(node, BoundDimStatement), arg)
Case BoundKind.Initializer
Return VisitInitializer(CType(node, BoundInitializer), arg)
Case BoundKind.FieldInitializer
Return VisitFieldInitializer(CType(node, BoundFieldInitializer), arg)
Case BoundKind.PropertyInitializer
Return VisitPropertyInitializer(CType(node, BoundPropertyInitializer), arg)
Case BoundKind.ParameterEqualsValue
Return VisitParameterEqualsValue(CType(node, BoundParameterEqualsValue), arg)
Case BoundKind.GlobalStatementInitializer
Return VisitGlobalStatementInitializer(CType(node, BoundGlobalStatementInitializer), arg)
Case BoundKind.Sequence
Return VisitSequence(CType(node, BoundSequence), arg)
Case BoundKind.ExpressionStatement
Return VisitExpressionStatement(CType(node, BoundExpressionStatement), arg)
Case BoundKind.IfStatement
Return VisitIfStatement(CType(node, BoundIfStatement), arg)
Case BoundKind.SelectStatement
Return VisitSelectStatement(CType(node, BoundSelectStatement), arg)
Case BoundKind.CaseBlock
Return VisitCaseBlock(CType(node, BoundCaseBlock), arg)
Case BoundKind.CaseStatement
Return VisitCaseStatement(CType(node, BoundCaseStatement), arg)
Case BoundKind.SimpleCaseClause
Return VisitSimpleCaseClause(CType(node, BoundSimpleCaseClause), arg)
Case BoundKind.RangeCaseClause
Return VisitRangeCaseClause(CType(node, BoundRangeCaseClause), arg)
Case BoundKind.RelationalCaseClause
Return VisitRelationalCaseClause(CType(node, BoundRelationalCaseClause), arg)
Case BoundKind.DoLoopStatement
Return VisitDoLoopStatement(CType(node, BoundDoLoopStatement), arg)
Case BoundKind.WhileStatement
Return VisitWhileStatement(CType(node, BoundWhileStatement), arg)
Case BoundKind.ForToUserDefinedOperators
Return VisitForToUserDefinedOperators(CType(node, BoundForToUserDefinedOperators), arg)
Case BoundKind.ForToStatement
Return VisitForToStatement(CType(node, BoundForToStatement), arg)
Case BoundKind.ForEachStatement
Return VisitForEachStatement(CType(node, BoundForEachStatement), arg)
Case BoundKind.ExitStatement
Return VisitExitStatement(CType(node, BoundExitStatement), arg)
Case BoundKind.ContinueStatement
Return VisitContinueStatement(CType(node, BoundContinueStatement), arg)
Case BoundKind.TryStatement
Return VisitTryStatement(CType(node, BoundTryStatement), arg)
Case BoundKind.CatchBlock
Return VisitCatchBlock(CType(node, BoundCatchBlock), arg)
Case BoundKind.Literal
Return VisitLiteral(CType(node, BoundLiteral), arg)
Case BoundKind.MeReference
Return VisitMeReference(CType(node, BoundMeReference), arg)
Case BoundKind.ValueTypeMeReference
Return VisitValueTypeMeReference(CType(node, BoundValueTypeMeReference), arg)
Case BoundKind.MyBaseReference
Return VisitMyBaseReference(CType(node, BoundMyBaseReference), arg)
Case BoundKind.MyClassReference
Return VisitMyClassReference(CType(node, BoundMyClassReference), arg)
Case BoundKind.PreviousSubmissionReference
Return VisitPreviousSubmissionReference(CType(node, BoundPreviousSubmissionReference), arg)
Case BoundKind.HostObjectMemberReference
Return VisitHostObjectMemberReference(CType(node, BoundHostObjectMemberReference), arg)
Case BoundKind.Local
Return VisitLocal(CType(node, BoundLocal), arg)
Case BoundKind.PseudoVariable
Return VisitPseudoVariable(CType(node, BoundPseudoVariable), arg)
Case BoundKind.Parameter
Return VisitParameter(CType(node, BoundParameter), arg)
Case BoundKind.ByRefArgumentPlaceholder
Return VisitByRefArgumentPlaceholder(CType(node, BoundByRefArgumentPlaceholder), arg)
Case BoundKind.ByRefArgumentWithCopyBack
Return VisitByRefArgumentWithCopyBack(CType(node, BoundByRefArgumentWithCopyBack), arg)
Case BoundKind.LateBoundArgumentSupportingAssignmentWithCapture
Return VisitLateBoundArgumentSupportingAssignmentWithCapture(CType(node, BoundLateBoundArgumentSupportingAssignmentWithCapture), arg)
Case BoundKind.LabelStatement
Return VisitLabelStatement(CType(node, BoundLabelStatement), arg)
Case BoundKind.Label
Return VisitLabel(CType(node, BoundLabel), arg)
Case BoundKind.GotoStatement
Return VisitGotoStatement(CType(node, BoundGotoStatement), arg)
Case BoundKind.StatementList
Return VisitStatementList(CType(node, BoundStatementList), arg)
Case BoundKind.ConditionalGoto
Return VisitConditionalGoto(CType(node, BoundConditionalGoto), arg)
Case BoundKind.WithStatement
Return VisitWithStatement(CType(node, BoundWithStatement), arg)
Case BoundKind.UnboundLambda
Return VisitUnboundLambda(CType(node, UnboundLambda), arg)
Case BoundKind.Lambda
Return VisitLambda(CType(node, BoundLambda), arg)
Case BoundKind.QueryExpression
Return VisitQueryExpression(CType(node, BoundQueryExpression), arg)
Case BoundKind.QuerySource
Return VisitQuerySource(CType(node, BoundQuerySource), arg)
Case BoundKind.ToQueryableCollectionConversion
Return VisitToQueryableCollectionConversion(CType(node, BoundToQueryableCollectionConversion), arg)
Case BoundKind.QueryableSource
Return VisitQueryableSource(CType(node, BoundQueryableSource), arg)
Case BoundKind.QueryClause
Return VisitQueryClause(CType(node, BoundQueryClause), arg)
Case BoundKind.Ordering
Return VisitOrdering(CType(node, BoundOrdering), arg)
Case BoundKind.QueryLambda
Return VisitQueryLambda(CType(node, BoundQueryLambda), arg)
Case BoundKind.RangeVariableAssignment
Return VisitRangeVariableAssignment(CType(node, BoundRangeVariableAssignment), arg)
Case BoundKind.GroupTypeInferenceLambda
Return VisitGroupTypeInferenceLambda(CType(node, GroupTypeInferenceLambda), arg)
Case BoundKind.AggregateClause
Return VisitAggregateClause(CType(node, BoundAggregateClause), arg)
Case BoundKind.GroupAggregation
Return VisitGroupAggregation(CType(node, BoundGroupAggregation), arg)
Case BoundKind.RangeVariable
Return VisitRangeVariable(CType(node, BoundRangeVariable), arg)
Case BoundKind.AddHandlerStatement
Return VisitAddHandlerStatement(CType(node, BoundAddHandlerStatement), arg)
Case BoundKind.RemoveHandlerStatement
Return VisitRemoveHandlerStatement(CType(node, BoundRemoveHandlerStatement), arg)
Case BoundKind.RaiseEventStatement
Return VisitRaiseEventStatement(CType(node, BoundRaiseEventStatement), arg)
Case BoundKind.UsingStatement
Return VisitUsingStatement(CType(node, BoundUsingStatement), arg)
Case BoundKind.SyncLockStatement
Return VisitSyncLockStatement(CType(node, BoundSyncLockStatement), arg)
Case BoundKind.XmlName
Return VisitXmlName(CType(node, BoundXmlName), arg)
Case BoundKind.XmlNamespace
Return VisitXmlNamespace(CType(node, BoundXmlNamespace), arg)
Case BoundKind.XmlDocument
Return VisitXmlDocument(CType(node, BoundXmlDocument), arg)
Case BoundKind.XmlDeclaration
Return VisitXmlDeclaration(CType(node, BoundXmlDeclaration), arg)
Case BoundKind.XmlProcessingInstruction
Return VisitXmlProcessingInstruction(CType(node, BoundXmlProcessingInstruction), arg)
Case BoundKind.XmlComment
Return VisitXmlComment(CType(node, BoundXmlComment), arg)
Case BoundKind.XmlAttribute
Return VisitXmlAttribute(CType(node, BoundXmlAttribute), arg)
Case BoundKind.XmlElement
Return VisitXmlElement(CType(node, BoundXmlElement), arg)
Case BoundKind.XmlMemberAccess
Return VisitXmlMemberAccess(CType(node, BoundXmlMemberAccess), arg)
Case BoundKind.XmlEmbeddedExpression
Return VisitXmlEmbeddedExpression(CType(node, BoundXmlEmbeddedExpression), arg)
Case BoundKind.XmlCData
Return VisitXmlCData(CType(node, BoundXmlCData), arg)
Case BoundKind.ResumeStatement
Return VisitResumeStatement(CType(node, BoundResumeStatement), arg)
Case BoundKind.OnErrorStatement
Return VisitOnErrorStatement(CType(node, BoundOnErrorStatement), arg)
Case BoundKind.UnstructuredExceptionHandlingStatement
Return VisitUnstructuredExceptionHandlingStatement(CType(node, BoundUnstructuredExceptionHandlingStatement), arg)
Case BoundKind.UnstructuredExceptionHandlingCatchFilter
Return VisitUnstructuredExceptionHandlingCatchFilter(CType(node, BoundUnstructuredExceptionHandlingCatchFilter), arg)
Case BoundKind.UnstructuredExceptionOnErrorSwitch
Return VisitUnstructuredExceptionOnErrorSwitch(CType(node, BoundUnstructuredExceptionOnErrorSwitch), arg)
Case BoundKind.UnstructuredExceptionResumeSwitch
Return VisitUnstructuredExceptionResumeSwitch(CType(node, BoundUnstructuredExceptionResumeSwitch), arg)
Case BoundKind.AwaitOperator
Return VisitAwaitOperator(CType(node, BoundAwaitOperator), arg)
Case BoundKind.SpillSequence
Return VisitSpillSequence(CType(node, BoundSpillSequence), arg)
Case BoundKind.StopStatement
Return VisitStopStatement(CType(node, BoundStopStatement), arg)
Case BoundKind.EndStatement
Return VisitEndStatement(CType(node, BoundEndStatement), arg)
Case BoundKind.MidResult
Return VisitMidResult(CType(node, BoundMidResult), arg)
Case BoundKind.ConditionalAccess
Return VisitConditionalAccess(CType(node, BoundConditionalAccess), arg)
Case BoundKind.ConditionalAccessReceiverPlaceholder
Return VisitConditionalAccessReceiverPlaceholder(CType(node, BoundConditionalAccessReceiverPlaceholder), arg)
Case BoundKind.LoweredConditionalAccess
Return VisitLoweredConditionalAccess(CType(node, BoundLoweredConditionalAccess), arg)
Case BoundKind.ComplexConditionalAccessReceiver
Return VisitComplexConditionalAccessReceiver(CType(node, BoundComplexConditionalAccessReceiver), arg)
Case BoundKind.NameOfOperator
Return VisitNameOfOperator(CType(node, BoundNameOfOperator), arg)
Case BoundKind.TypeAsValueExpression
Return VisitTypeAsValueExpression(CType(node, BoundTypeAsValueExpression), arg)
Case BoundKind.InterpolatedStringExpression
Return VisitInterpolatedStringExpression(CType(node, BoundInterpolatedStringExpression), arg)
Case BoundKind.Interpolation
Return VisitInterpolation(CType(node, BoundInterpolation), arg)
End Select
Return DefaultVisit(node, arg)
End Function
End Class
Friend MustInherit Partial Class BoundTreeVisitor(Of A, R)
Public Overridable Function VisitTypeArguments(node As BoundTypeArguments, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitOmittedArgument(node As BoundOmittedArgument, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRValuePlaceholder(node As BoundRValuePlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLValuePlaceholder(node As BoundLValuePlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDup(node As BoundDup, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBadExpression(node As BoundBadExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBadStatement(node As BoundBadStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitParenthesized(node As BoundParenthesized, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBadVariable(node As BoundBadVariable, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayAccess(node As BoundArrayAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayLength(node As BoundArrayLength, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGetType(node As BoundGetType, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitFieldInfo(node As BoundFieldInfo, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMethodInfo(node As BoundMethodInfo, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeExpression(node As BoundTypeExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNamespaceExpression(node As BoundNamespaceExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMethodDefIndex(node As BoundMethodDefIndex, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitModuleVersionId(node As BoundModuleVersionId, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitModuleVersionIdString(node As BoundModuleVersionIdString, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnaryOperator(node As BoundUnaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBinaryOperator(node As BoundBinaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAssignmentOperator(node As BoundAssignmentOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitReferenceAssignment(node As BoundReferenceAssignment, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAddressOfOperator(node As BoundAddressOfOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConversion(node As BoundConversion, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRelaxationLambda(node As BoundRelaxationLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConvertedTupleElements(node As BoundConvertedTupleElements, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUserDefinedConversion(node As BoundUserDefinedConversion, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDirectCast(node As BoundDirectCast, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTryCast(node As BoundTryCast, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeOf(node As BoundTypeOf, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequencePoint(node As BoundSequencePoint, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequencePointExpression(node As BoundSequencePointExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNoOpStatement(node As BoundNoOpStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMethodGroup(node As BoundMethodGroup, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPropertyGroup(node As BoundPropertyGroup, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitReturnStatement(node As BoundReturnStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitYieldStatement(node As BoundYieldStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitThrowStatement(node As BoundThrowStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRedimStatement(node As BoundRedimStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRedimClause(node As BoundRedimClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitEraseStatement(node As BoundEraseStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCall(node As BoundCall, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAttribute(node As BoundAttribute, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateMemberAccess(node As BoundLateMemberAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateInvocation(node As BoundLateInvocation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTupleLiteral(node As BoundTupleLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitObjectCreationExpression(node As BoundObjectCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNewT(node As BoundNewT, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayCreation(node As BoundArrayCreation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayLiteral(node As BoundArrayLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitArrayInitialization(node As BoundArrayInitialization, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitFieldAccess(node As BoundFieldAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPropertyAccess(node As BoundPropertyAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitEventAccess(node As BoundEventAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitBlock(node As BoundBlock, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitStateMachineScope(node As BoundStateMachineScope, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLocalDeclaration(node As BoundLocalDeclaration, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDimStatement(node As BoundDimStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInitializer(node As BoundInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitFieldInitializer(node As BoundFieldInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPropertyInitializer(node As BoundPropertyInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitParameterEqualsValue(node As BoundParameterEqualsValue, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSequence(node As BoundSequence, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitExpressionStatement(node As BoundExpressionStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitIfStatement(node As BoundIfStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSelectStatement(node As BoundSelectStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCaseBlock(node As BoundCaseBlock, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCaseStatement(node As BoundCaseStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSimpleCaseClause(node As BoundSimpleCaseClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRangeCaseClause(node As BoundRangeCaseClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRelationalCaseClause(node As BoundRelationalCaseClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitDoLoopStatement(node As BoundDoLoopStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWhileStatement(node As BoundWhileStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitForToStatement(node As BoundForToStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitForEachStatement(node As BoundForEachStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitExitStatement(node As BoundExitStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitContinueStatement(node As BoundContinueStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTryStatement(node As BoundTryStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitCatchBlock(node As BoundCatchBlock, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLiteral(node As BoundLiteral, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMeReference(node As BoundMeReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitValueTypeMeReference(node As BoundValueTypeMeReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMyBaseReference(node As BoundMyBaseReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMyClassReference(node As BoundMyClassReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLocal(node As BoundLocal, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitPseudoVariable(node As BoundPseudoVariable, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitParameter(node As BoundParameter, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLabelStatement(node As BoundLabelStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLabel(node As BoundLabel, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGotoStatement(node As BoundGotoStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitStatementList(node As BoundStatementList, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConditionalGoto(node As BoundConditionalGoto, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitWithStatement(node As BoundWithStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnboundLambda(node As UnboundLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLambda(node As BoundLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryExpression(node As BoundQueryExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQuerySource(node As BoundQuerySource, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryableSource(node As BoundQueryableSource, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryClause(node As BoundQueryClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitOrdering(node As BoundOrdering, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitQueryLambda(node As BoundQueryLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAggregateClause(node As BoundAggregateClause, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitGroupAggregation(node As BoundGroupAggregation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRangeVariable(node As BoundRangeVariable, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAddHandlerStatement(node As BoundAddHandlerStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitRaiseEventStatement(node As BoundRaiseEventStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUsingStatement(node As BoundUsingStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSyncLockStatement(node As BoundSyncLockStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlName(node As BoundXmlName, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlNamespace(node As BoundXmlNamespace, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlDocument(node As BoundXmlDocument, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlDeclaration(node As BoundXmlDeclaration, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlComment(node As BoundXmlComment, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlAttribute(node As BoundXmlAttribute, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlElement(node As BoundXmlElement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlMemberAccess(node As BoundXmlMemberAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitXmlCData(node As BoundXmlCData, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitResumeStatement(node As BoundResumeStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitOnErrorStatement(node As BoundOnErrorStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitAwaitOperator(node As BoundAwaitOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitSpillSequence(node As BoundSpillSequence, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitStopStatement(node As BoundStopStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitEndStatement(node As BoundEndStatement, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitMidResult(node As BoundMidResult, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConditionalAccess(node As BoundConditionalAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitNameOfOperator(node As BoundNameOfOperator, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
Public Overridable Function VisitInterpolation(node As BoundInterpolation, arg As A) As R
Return Me.DefaultVisit(node, arg)
End Function
End Class
Friend MustInherit Partial Class BoundTreeVisitor
Public Overridable Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDup(node As BoundDup) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBadStatement(node As BoundBadStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayLength(node As BoundArrayLength) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGetType(node As BoundGetType) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeExpression(node As BoundTypeExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNamespaceExpression(node As BoundNamespaceExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMethodDefIndex(node As BoundMethodDefIndex) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitModuleVersionId(node As BoundModuleVersionId) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitModuleVersionIdString(node As BoundModuleVersionIdString) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConversion(node As BoundConversion) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRelaxationLambda(node As BoundRelaxationLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConvertedTupleElements(node As BoundConvertedTupleElements) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDirectCast(node As BoundDirectCast) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTryCast(node As BoundTryCast) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeOf(node As BoundTypeOf) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequencePointExpression(node As BoundSequencePointExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNoOpStatement(node As BoundNoOpStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRedimClause(node As BoundRedimClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitEraseStatement(node As BoundEraseStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCall(node As BoundCall) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAttribute(node As BoundAttribute) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNewT(node As BoundNewT) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitEventAccess(node As BoundEventAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitBlock(node As BoundBlock) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitStateMachineScope(node As BoundStateMachineScope) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInitializer(node As BoundInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitParameterEqualsValue(node As BoundParameterEqualsValue) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSequence(node As BoundSequence) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitIfStatement(node As BoundIfStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCaseStatement(node As BoundCaseStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSimpleCaseClause(node As BoundSimpleCaseClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRangeCaseClause(node As BoundRangeCaseClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRelationalCaseClause(node As BoundRelationalCaseClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitDoLoopStatement(node As BoundDoLoopStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitForToStatement(node As BoundForToStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitExitStatement(node As BoundExitStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitContinueStatement(node As BoundContinueStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLiteral(node As BoundLiteral) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLocal(node As BoundLocal) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitPseudoVariable(node As BoundPseudoVariable) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitParameter(node As BoundParameter) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLabel(node As BoundLabel) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitStatementList(node As BoundStatementList) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLambda(node As BoundLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQuerySource(node As BoundQuerySource) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryClause(node As BoundQueryClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitOrdering(node As BoundOrdering) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitGroupAggregation(node As BoundGroupAggregation) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAddHandlerStatement(node As BoundAddHandlerStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlName(node As BoundXmlName) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitStopStatement(node As BoundStopStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitEndStatement(node As BoundEndStatement) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitMidResult(node As BoundMidResult) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitNameOfOperator(node As BoundNameOfOperator) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode
Return Me.DefaultVisit(node)
End Function
Public Overridable Function VisitInterpolation(node As BoundInterpolation) As BoundNode
Return Me.DefaultVisit(node)
End Function
End Class
Friend MustInherit Partial Class BoundTreeWalker
Inherits BoundTreeVisitor
Public Overrides Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode
Me.Visit(node.UnderlyingLValue)
Return Nothing
End Function
Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitDup(node As BoundDup) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Me.VisitList(node.ChildBoundNodes)
Return Nothing
End Function
Public Overrides Function VisitBadStatement(node As BoundBadStatement) As BoundNode
Me.VisitList(node.ChildBoundNodes)
Return Nothing
End Function
Public Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
Me.Visit(node.Expression)
Me.VisitList(node.Indices)
Return Nothing
End Function
Public Overrides Function VisitArrayLength(node As BoundArrayLength) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitGetType(node As BoundGetType) As BoundNode
Me.Visit(node.SourceType)
Return Nothing
End Function
Public Overrides Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitTypeExpression(node As BoundTypeExpression) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitNamespaceExpression(node As BoundNamespaceExpression) As BoundNode
Me.Visit(node.UnevaluatedReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitMethodDefIndex(node As BoundMethodDefIndex) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitModuleVersionId(node As BoundModuleVersionId) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitModuleVersionIdString(node As BoundModuleVersionIdString) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
Me.Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Me.Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Me.Visit(node.Left)
Me.Visit(node.Right)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Me.Visit(node.LeftOperand)
Me.Visit(node.LeftOperandPlaceholder)
Me.Visit(node.LeftTest)
Me.Visit(node.BitwiseOperator)
Return Nothing
End Function
Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Me.Visit(node.Left)
Me.Visit(node.LeftOnTheRightOpt)
Me.Visit(node.Right)
Return Nothing
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
Me.Visit(node.ByRefLocal)
Me.Visit(node.LValue)
Return Nothing
End Function
Public Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Me.Visit(node.MethodGroup)
Return Nothing
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
Me.Visit(node.Condition)
Me.Visit(node.WhenTrue)
Me.Visit(node.WhenFalse)
Return Nothing
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
Me.Visit(node.TestExpression)
Me.Visit(node.ElseExpression)
Return Nothing
End Function
Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.ExtendedInfoOpt)
Return Nothing
End Function
Public Overrides Function VisitRelaxationLambda(node As BoundRelaxationLambda) As BoundNode
Me.Visit(node.Lambda)
Me.Visit(node.ReceiverPlaceholderOpt)
Return Nothing
End Function
Public Overrides Function VisitConvertedTupleElements(node As BoundConvertedTupleElements) As BoundNode
Me.VisitList(node.ElementPlaceholders)
Me.VisitList(node.ConvertedElements)
Return Nothing
End Function
Public Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.RelaxationLambdaOpt)
Return Nothing
End Function
Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.RelaxationLambdaOpt)
Return Nothing
End Function
Public Overrides Function VisitTypeOf(node As BoundTypeOf) As BoundNode
Me.Visit(node.Operand)
Return Nothing
End Function
Public Overrides Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode
Me.Visit(node.StatementOpt)
Return Nothing
End Function
Public Overrides Function VisitSequencePointExpression(node As BoundSequencePointExpression) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode
Me.Visit(node.StatementOpt)
Return Nothing
End Function
Public Overrides Function VisitNoOpStatement(node As BoundNoOpStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Me.Visit(node.TypeArgumentsOpt)
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Me.Visit(node.ExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode
Me.Visit(node.ExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode
Me.VisitList(node.Clauses)
Return Nothing
End Function
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
Me.Visit(node.Operand)
Me.VisitList(node.Indices)
Return Nothing
End Function
Public Overrides Function VisitEraseStatement(node As BoundEraseStatement) As BoundNode
Me.VisitList(node.Clauses)
Return Nothing
End Function
Public Overrides Function VisitCall(node As BoundCall) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitAttribute(node As BoundAttribute) As BoundNode
Me.VisitList(node.ConstructorArguments)
Me.VisitList(node.NamedArguments)
Return Nothing
End Function
Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.Visit(node.TypeArgumentsOpt)
Return Nothing
End Function
Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Me.Visit(node.Member)
Me.VisitList(node.ArgumentsOpt)
Return Nothing
End Function
Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Me.Visit(node.MemberAccess)
Return Nothing
End Function
Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
Me.VisitList(node.Arguments)
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Me.VisitList(node.Declarations)
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Me.Visit(node.PlaceholderOpt)
Me.VisitList(node.Initializers)
Return Nothing
End Function
Public Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Me.Visit(node.PlaceholderOpt)
Me.VisitList(node.Initializers)
Return Nothing
End Function
Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.Visit(node.RelaxationLambdaOpt)
Me.Visit(node.RelaxationReceiverPlaceholderOpt)
Return Nothing
End Function
Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode
Me.VisitList(node.Bounds)
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Me.VisitList(node.Bounds)
Me.Visit(node.Initializer)
Return Nothing
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
Me.VisitList(node.Initializers)
Return Nothing
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Me.VisitList(node.Arguments)
Return Nothing
End Function
Public Overrides Function VisitEventAccess(node As BoundEventAccess) As BoundNode
Me.Visit(node.ReceiverOpt)
Return Nothing
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Me.VisitList(node.Statements)
Return Nothing
End Function
Public Overrides Function VisitStateMachineScope(node As BoundStateMachineScope) As BoundNode
Me.Visit(node.Statement)
Return Nothing
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Me.Visit(node.DeclarationInitializerOpt)
Me.Visit(node.IdentifierInitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Me.VisitList(node.LocalDeclarations)
Me.Visit(node.Initializer)
Return Nothing
End Function
Public Overrides Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Me.VisitList(node.LocalDeclarations)
Me.Visit(node.InitializerOpt)
Return Nothing
End Function
Public Overrides Function VisitInitializer(node As BoundInitializer) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Me.Visit(node.MemberAccessExpressionOpt)
Me.Visit(node.InitialValue)
Return Nothing
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Me.Visit(node.MemberAccessExpressionOpt)
Me.Visit(node.InitialValue)
Return Nothing
End Function
Public Overrides Function VisitParameterEqualsValue(node As BoundParameterEqualsValue) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer) As BoundNode
Me.Visit(node.Statement)
Return Nothing
End Function
Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode
Me.VisitList(node.SideEffects)
Me.Visit(node.ValueOpt)
Return Nothing
End Function
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitIfStatement(node As BoundIfStatement) As BoundNode
Me.Visit(node.Condition)
Me.Visit(node.Consequence)
Me.Visit(node.AlternativeOpt)
Return Nothing
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Me.Visit(node.ExpressionStatement)
Me.Visit(node.ExprPlaceholderOpt)
Me.VisitList(node.CaseBlocks)
Return Nothing
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Me.Visit(node.CaseStatement)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitCaseStatement(node As BoundCaseStatement) As BoundNode
Me.VisitList(node.CaseClauses)
Me.Visit(node.ConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitSimpleCaseClause(node As BoundSimpleCaseClause) As BoundNode
Me.Visit(node.ValueOpt)
Me.Visit(node.ConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitRangeCaseClause(node As BoundRangeCaseClause) As BoundNode
Me.Visit(node.LowerBoundOpt)
Me.Visit(node.UpperBoundOpt)
Me.Visit(node.LowerBoundConditionOpt)
Me.Visit(node.UpperBoundConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitRelationalCaseClause(node As BoundRelationalCaseClause) As BoundNode
Me.Visit(node.ValueOpt)
Me.Visit(node.ConditionOpt)
Return Nothing
End Function
Public Overrides Function VisitDoLoopStatement(node As BoundDoLoopStatement) As BoundNode
Me.Visit(node.TopConditionOpt)
Me.Visit(node.BottomConditionOpt)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Me.Visit(node.Condition)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators) As BoundNode
Me.Visit(node.LeftOperandPlaceholder)
Me.Visit(node.RightOperandPlaceholder)
Me.Visit(node.Addition)
Me.Visit(node.Subtraction)
Me.Visit(node.LessThanOrEqual)
Me.Visit(node.GreaterThanOrEqual)
Return Nothing
End Function
Public Overrides Function VisitForToStatement(node As BoundForToStatement) As BoundNode
Me.Visit(node.InitialValue)
Me.Visit(node.LimitValue)
Me.Visit(node.StepValue)
Me.Visit(node.OperatorsOpt)
Me.Visit(node.ControlVariable)
Me.Visit(node.Body)
Me.VisitList(node.NextVariablesOpt)
Return Nothing
End Function
Public Overrides Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
Me.Visit(node.Collection)
Me.Visit(node.ControlVariable)
Me.Visit(node.Body)
Me.VisitList(node.NextVariablesOpt)
Return Nothing
End Function
Public Overrides Function VisitExitStatement(node As BoundExitStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitContinueStatement(node As BoundContinueStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Me.Visit(node.TryBlock)
Me.VisitList(node.CatchBlocks)
Me.Visit(node.FinallyBlockOpt)
Return Nothing
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Me.Visit(node.ExceptionSourceOpt)
Me.Visit(node.ErrorLineNumberOpt)
Me.Visit(node.ExceptionFilterOpt)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitLiteral(node As BoundLiteral) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitPseudoVariable(node As BoundPseudoVariable) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Me.Visit(node.OriginalArgument)
Me.Visit(node.InConversion)
Me.Visit(node.InPlaceholder)
Me.Visit(node.OutConversion)
Me.Visit(node.OutPlaceholder)
Return Nothing
End Function
Public Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Me.Visit(node.OriginalArgument)
Return Nothing
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLabel(node As BoundLabel) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Me.Visit(node.LabelExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitStatementList(node As BoundStatementList) As BoundNode
Me.VisitList(node.Statements)
Return Nothing
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
Me.Visit(node.Condition)
Return Nothing
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Me.Visit(node.OriginalExpression)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
Me.Visit(node.LastOperator)
Return Nothing
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
Me.Visit(node.ConversionCall)
Return Nothing
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
Me.Visit(node.Source)
Return Nothing
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering) As BoundNode
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
Me.Visit(node.CapturedGroupOpt)
Me.Visit(node.GroupPlaceholderOpt)
Me.Visit(node.UnderlyingExpression)
Return Nothing
End Function
Public Overrides Function VisitGroupAggregation(node As BoundGroupAggregation) As BoundNode
Me.Visit(node.Group)
Return Nothing
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitAddHandlerStatement(node As BoundAddHandlerStatement) As BoundNode
Me.Visit(node.EventAccess)
Me.Visit(node.Handler)
Return Nothing
End Function
Public Overrides Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement) As BoundNode
Me.Visit(node.EventAccess)
Me.Visit(node.Handler)
Return Nothing
End Function
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Me.Visit(node.EventInvocation)
Return Nothing
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Me.VisitList(node.ResourceList)
Me.Visit(node.ResourceExpressionOpt)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Me.Visit(node.LockExpression)
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Me.Visit(node.XmlNamespace)
Me.Visit(node.LocalName)
Return Nothing
End Function
Public Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Me.Visit(node.XmlNamespace)
Return Nothing
End Function
Public Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Me.Visit(node.Declaration)
Me.VisitList(node.ChildNodes)
Return Nothing
End Function
Public Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Me.Visit(node.Version)
Me.Visit(node.Encoding)
Me.Visit(node.Standalone)
Return Nothing
End Function
Public Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Me.Visit(node.Target)
Me.Visit(node.Data)
Return Nothing
End Function
Public Overrides Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Me.Visit(node.Name)
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Me.Visit(node.Argument)
Me.VisitList(node.ChildNodes)
Return Nothing
End Function
Public Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Me.Visit(node.MemberAccess)
Return Nothing
End Function
Public Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Me.Visit(node.Value)
Return Nothing
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
Me.Visit(node.LabelExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
Me.Visit(node.LabelExpressionOpt)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement) As BoundNode
Me.Visit(node.Body)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter) As BoundNode
Me.Visit(node.ActiveHandlerLocal)
Me.Visit(node.ResumeTargetLocal)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode
Me.Visit(node.Value)
Me.VisitList(node.Jumps)
Return Nothing
End Function
Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode
Me.Visit(node.ResumeTargetTemporary)
Me.Visit(node.ResumeLabel)
Me.Visit(node.ResumeNextLabel)
Me.VisitList(node.Jumps)
Return Nothing
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Me.Visit(node.Operand)
Me.Visit(node.AwaitableInstancePlaceholder)
Me.Visit(node.GetAwaiter)
Me.Visit(node.AwaiterInstancePlaceholder)
Me.Visit(node.IsCompleted)
Me.Visit(node.GetResult)
Return Nothing
End Function
Public Overrides Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode
Me.VisitList(node.Statements)
Me.Visit(node.ValueOpt)
Return Nothing
End Function
Public Overrides Function VisitStopStatement(node As BoundStopStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitEndStatement(node As BoundEndStatement) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitMidResult(node As BoundMidResult) As BoundNode
Me.Visit(node.Original)
Me.Visit(node.Start)
Me.Visit(node.LengthOpt)
Me.Visit(node.Source)
Return Nothing
End Function
Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode
Me.Visit(node.Receiver)
Me.Visit(node.Placeholder)
Me.Visit(node.AccessExpression)
Return Nothing
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Return Nothing
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
Me.Visit(node.ReceiverOrCondition)
Me.Visit(node.WhenNotNull)
Me.Visit(node.WhenNullOpt)
Return Nothing
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
Me.Visit(node.ValueTypeReceiver)
Me.Visit(node.ReferenceTypeReceiver)
Return Nothing
End Function
Public Overrides Function VisitNameOfOperator(node As BoundNameOfOperator) As BoundNode
Me.Visit(node.Argument)
Return Nothing
End Function
Public Overrides Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression) As BoundNode
Me.Visit(node.Expression)
Return Nothing
End Function
Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode
Me.VisitList(node.Contents)
Return Nothing
End Function
Public Overrides Function VisitInterpolation(node As BoundInterpolation) As BoundNode
Me.Visit(node.Expression)
Me.Visit(node.AlignmentOpt)
Me.Visit(node.FormatStringOpt)
Return Nothing
End Function
End Class
Friend MustInherit Partial Class BoundTreeRewriter
Inherits BoundTreeVisitor
Public Overrides Function VisitTypeArguments(node As BoundTypeArguments) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Arguments)
End Function
Public Overrides Function VisitOmittedArgument(node As BoundOmittedArgument) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper) As BoundNode
Dim underlyingLValue As BoundExpression = DirectCast(Me.Visit(node.UnderlyingLValue), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingLValue, type)
End Function
Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitDup(node As BoundDup) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsReference, type)
End Function
Public Overrides Function VisitBadExpression(node As BoundBadExpression) As BoundNode
Dim childBoundNodes As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ChildBoundNodes)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.ResultKind, node.Symbols, childBoundNodes, type)
End Function
Public Overrides Function VisitBadStatement(node As BoundBadStatement) As BoundNode
Dim childBoundNodes As ImmutableArray(Of BoundNode) = Me.VisitList(node.ChildBoundNodes)
Return node.Update(childBoundNodes)
End Function
Public Overrides Function VisitParenthesized(node As BoundParenthesized) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitBadVariable(node As BoundBadVariable) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, node.IsLValue, type)
End Function
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim indices As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Indices)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, indices, node.IsLValue, type)
End Function
Public Overrides Function VisitArrayLength(node As BoundArrayLength) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitGetType(node As BoundGetType) As BoundNode
Dim sourceType As BoundTypeExpression = DirectCast(Me.Visit(node.SourceType), BoundTypeExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(sourceType, type)
End Function
Public Overrides Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Field, type)
End Function
Public Overrides Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Method, type)
End Function
Public Overrides Function VisitTypeExpression(node As BoundTypeExpression) As BoundNode
Dim unevaluatedReceiverOpt As BoundExpression = node.UnevaluatedReceiverOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(unevaluatedReceiverOpt, node.AliasOpt, type)
End Function
Public Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Data, type)
End Function
Public Overrides Function VisitNamespaceExpression(node As BoundNamespaceExpression) As BoundNode
Dim unevaluatedReceiverOpt As BoundExpression = DirectCast(Me.Visit(node.UnevaluatedReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(unevaluatedReceiverOpt, node.AliasOpt, node.NamespaceSymbol)
End Function
Public Overrides Function VisitMethodDefIndex(node As BoundMethodDefIndex) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Method, type)
End Function
Public Overrides Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.AnalysisKind, node.IsLValue, type)
End Function
Public Overrides Function VisitModuleVersionId(node As BoundModuleVersionId) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsLValue, type)
End Function
Public Overrides Function VisitModuleVersionIdString(node As BoundModuleVersionIdString) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Document, type)
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, operand, node.Checked, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, underlyingExpression, type)
End Function
Public Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, type)
End Function
Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator) As BoundNode
Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression)
Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, left, right, node.Checked, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.OperatorKind, underlyingExpression, node.Checked, type)
End Function
Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode
Dim leftOperand As BoundExpression = DirectCast(Me.Visit(node.LeftOperand), BoundExpression)
Dim leftOperandPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.LeftOperandPlaceholder), BoundRValuePlaceholder)
Dim leftTest As BoundExpression = DirectCast(Me.Visit(node.LeftTest), BoundExpression)
Dim bitwiseOperator As BoundUserDefinedBinaryOperator = DirectCast(Me.Visit(node.BitwiseOperator), BoundUserDefinedBinaryOperator)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(leftOperand, leftOperandPlaceholder, leftTest, bitwiseOperator, type)
End Function
Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode
Dim left As BoundExpression = DirectCast(Me.Visit(node.Left), BoundExpression)
Dim leftOnTheRightOpt As BoundCompoundAssignmentTargetPlaceholder = DirectCast(Me.Visit(node.LeftOnTheRightOpt), BoundCompoundAssignmentTargetPlaceholder)
Dim right As BoundExpression = DirectCast(Me.Visit(node.Right), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(left, leftOnTheRightOpt, right, node.SuppressObjectClone, type)
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment) As BoundNode
Dim byRefLocal As BoundLocal = DirectCast(Me.Visit(node.ByRefLocal), BoundLocal)
Dim lValue As BoundExpression = DirectCast(Me.Visit(node.LValue), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(byRefLocal, lValue, node.IsLValue, type)
End Function
Public Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator) As BoundNode
Dim methodGroup As BoundMethodGroup = DirectCast(Me.Visit(node.MethodGroup), BoundMethodGroup)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.WithDependencies, methodGroup)
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Dim whenTrue As BoundExpression = DirectCast(Me.Visit(node.WhenTrue), BoundExpression)
Dim whenFalse As BoundExpression = DirectCast(Me.Visit(node.WhenFalse), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(condition, whenTrue, whenFalse, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression) As BoundNode
Dim testExpression As BoundExpression = DirectCast(Me.Visit(node.TestExpression), BoundExpression)
Dim convertedTestExpression As BoundExpression = node.ConvertedTestExpression
Dim testExpressionPlaceholder As BoundRValuePlaceholder = node.TestExpressionPlaceholder
Dim elseExpression As BoundExpression = DirectCast(Me.Visit(node.ElseExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(testExpression, convertedTestExpression, testExpressionPlaceholder, elseExpression, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim extendedInfoOpt As BoundExtendedConversionInfo = DirectCast(Me.Visit(node.ExtendedInfoOpt), BoundExtendedConversionInfo)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, extendedInfoOpt, type)
End Function
Public Overrides Function VisitRelaxationLambda(node As BoundRelaxationLambda) As BoundNode
Dim lambda As BoundLambda = DirectCast(Me.Visit(node.Lambda), BoundLambda)
Dim receiverPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.ReceiverPlaceholderOpt), BoundRValuePlaceholder)
Return node.Update(lambda, receiverPlaceholderOpt)
End Function
Public Overrides Function VisitConvertedTupleElements(node As BoundConvertedTupleElements) As BoundNode
Dim elementPlaceholders As ImmutableArray(Of BoundRValuePlaceholder) = Me.VisitList(node.ElementPlaceholders)
Dim convertedElements As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ConvertedElements)
Return node.Update(elementPlaceholders, convertedElements)
End Function
Public Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingExpression, node.InOutConversionFlags, type)
End Function
Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim relaxationLambdaOpt As BoundLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.ConversionKind, node.SuppressVirtualCalls, node.ConstantValueOpt, relaxationLambdaOpt, type)
End Function
Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim relaxationLambdaOpt As BoundLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.ConversionKind, node.ConstantValueOpt, relaxationLambdaOpt, type)
End Function
Public Overrides Function VisitTypeOf(node As BoundTypeOf) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim targetType as TypeSymbol = Me.VisitType(node.TargetType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, node.IsTypeOfIsNotExpression, targetType, type)
End Function
Public Overrides Function VisitSequencePoint(node As BoundSequencePoint) As BoundNode
Dim statementOpt As BoundStatement = DirectCast(Me.Visit(node.StatementOpt), BoundStatement)
Return node.Update(statementOpt)
End Function
Public Overrides Function VisitSequencePointExpression(node As BoundSequencePointExpression) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan) As BoundNode
Dim statementOpt As BoundStatement = DirectCast(Me.Visit(node.StatementOpt), BoundStatement)
Return node.Update(statementOpt, node.Span)
End Function
Public Overrides Function VisitNoOpStatement(node As BoundNoOpStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitMethodGroup(node As BoundMethodGroup) As BoundNode
Dim typeArgumentsOpt As BoundTypeArguments = DirectCast(Me.Visit(node.TypeArgumentsOpt), BoundTypeArguments)
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(typeArgumentsOpt, node.Methods, node.PendingExtensionMethodsOpt, node.ResultKind, receiverOpt, node.QualificationKind)
End Function
Public Overrides Function VisitPropertyGroup(node As BoundPropertyGroup) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Properties, node.ResultKind, receiverOpt, node.QualificationKind)
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Dim expressionOpt As BoundExpression = DirectCast(Me.Visit(node.ExpressionOpt), BoundExpression)
Return node.Update(expressionOpt, node.FunctionLocalOpt, node.ExitLabelOpt)
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Return node.Update(expression)
End Function
Public Overrides Function VisitThrowStatement(node As BoundThrowStatement) As BoundNode
Dim expressionOpt As BoundExpression = DirectCast(Me.Visit(node.ExpressionOpt), BoundExpression)
Return node.Update(expressionOpt)
End Function
Public Overrides Function VisitRedimStatement(node As BoundRedimStatement) As BoundNode
Dim clauses As ImmutableArray(Of BoundRedimClause) = Me.VisitList(node.Clauses)
Return node.Update(clauses)
End Function
Public Overrides Function VisitRedimClause(node As BoundRedimClause) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim indices As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Indices)
Return node.Update(operand, indices, node.ArrayTypeOpt, node.Preserve)
End Function
Public Overrides Function VisitEraseStatement(node As BoundEraseStatement) As BoundNode
Dim clauses As ImmutableArray(Of BoundAssignmentOperator) = Me.VisitList(node.Clauses)
Return node.Update(clauses)
End Function
Public Overrides Function VisitCall(node As BoundCall) As BoundNode
Dim methodGroupOpt As BoundMethodGroup = node.MethodGroupOpt
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Method, methodGroupOpt, receiverOpt, arguments, node.DefaultArguments, node.ConstantValueOpt, node.IsLValue, node.SuppressObjectClone, type)
End Function
Public Overrides Function VisitAttribute(node As BoundAttribute) As BoundNode
Dim constructorArguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ConstructorArguments)
Dim namedArguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.NamedArguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Constructor, constructorArguments, namedArguments, node.ResultKind, type)
End Function
Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim typeArgumentsOpt As BoundTypeArguments = DirectCast(Me.Visit(node.TypeArgumentsOpt), BoundTypeArguments)
Dim containerTypeOpt as TypeSymbol = Me.VisitType(node.ContainerTypeOpt)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.NameOpt, containerTypeOpt, receiverOpt, typeArgumentsOpt, node.AccessKind, type)
End Function
Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode
Dim member As BoundExpression = DirectCast(Me.Visit(node.Member), BoundExpression)
Dim argumentsOpt As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ArgumentsOpt)
Dim methodOrPropertyGroupOpt As BoundMethodOrPropertyGroup = node.MethodOrPropertyGroupOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(member, argumentsOpt, node.ArgumentNamesOpt, node.AccessKind, methodOrPropertyGroupOpt, type)
End Function
Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode
Dim memberAccess As BoundLateMemberAccess = DirectCast(Me.Visit(node.MemberAccess), BoundLateMemberAccess)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, memberAccess, type)
End Function
Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.InferredType, node.ArgumentNamesOpt, node.InferredNamesOpt, arguments, type)
End Function
Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim naturalTypeOpt as TypeSymbol = Me.VisitType(node.NaturalTypeOpt)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(naturalTypeOpt, arguments, type)
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode
Dim methodGroupOpt As BoundMethodGroup = node.MethodGroupOpt
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim initializerOpt As BoundObjectInitializerExpressionBase = DirectCast(Me.Visit(node.InitializerOpt), BoundObjectInitializerExpressionBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.ConstructorOpt, methodGroupOpt, arguments, node.DefaultArguments, initializerOpt, type)
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode
Dim initializerOpt As BoundObjectInitializerExpressionBase = DirectCast(Me.Visit(node.InitializerOpt), BoundObjectInitializerExpressionBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.GuidString, initializerOpt, type)
End Function
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode
Dim declarations As ImmutableArray(Of BoundAnonymousTypePropertyAccess) = Me.VisitList(node.Declarations)
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.BinderOpt, declarations, arguments, type)
End Function
Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.PropertyIndex, type)
End Function
Public Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, value, type)
End Function
Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode
Dim placeholderOpt As BoundWithLValueExpressionPlaceholder = DirectCast(Me.Visit(node.PlaceholderOpt), BoundWithLValueExpressionPlaceholder)
Dim initializers As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Initializers)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.CreateTemporaryLocalForInitialization, placeholderOpt, initializers, type)
End Function
Public Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression) As BoundNode
Dim placeholderOpt As BoundWithLValueExpressionPlaceholder = DirectCast(Me.Visit(node.PlaceholderOpt), BoundWithLValueExpressionPlaceholder)
Dim initializers As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Initializers)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(placeholderOpt, initializers, type)
End Function
Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode
Dim initializerOpt As BoundObjectInitializerExpressionBase = DirectCast(Me.Visit(node.InitializerOpt), BoundObjectInitializerExpressionBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(initializerOpt, type)
End Function
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim relaxationLambdaOpt As BoundLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda)
Dim relaxationReceiverPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.RelaxationReceiverPlaceholderOpt), BoundRValuePlaceholder)
Dim methodGroupOpt As BoundMethodGroup = node.MethodGroupOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOpt, node.Method, relaxationLambdaOpt, relaxationReceiverPlaceholderOpt, methodGroupOpt, type)
End Function
Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode
Dim bounds As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Bounds)
Dim initializerOpt As BoundArrayInitialization = DirectCast(Me.Visit(node.InitializerOpt), BoundArrayInitialization)
Dim arrayLiteralOpt As BoundArrayLiteral = node.ArrayLiteralOpt
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsParamArrayArgument, bounds, initializerOpt, arrayLiteralOpt, node.ArrayLiteralConversion, type)
End Function
Public Overrides Function VisitArrayLiteral(node As BoundArrayLiteral) As BoundNode
Dim bounds As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Bounds)
Dim initializer As BoundArrayInitialization = DirectCast(Me.Visit(node.Initializer), BoundArrayInitialization)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.HasDominantType, node.NumberOfCandidates, node.InferredType, bounds, initializer, node.Binder)
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization) As BoundNode
Dim initializers As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Initializers)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(initializers, type)
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOpt, node.FieldSymbol, node.IsLValue, node.SuppressVirtualCalls, node.ConstantsInProgressOpt, type)
End Function
Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode
Dim propertyGroupOpt As BoundPropertyGroup = node.PropertyGroupOpt
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim arguments As ImmutableArray(Of BoundExpression) = Me.VisitList(node.Arguments)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.PropertySymbol, propertyGroupOpt, node.AccessKind, node.IsWriteable, node.IsLValue, receiverOpt, arguments, node.DefaultArguments, type)
End Function
Public Overrides Function VisitEventAccess(node As BoundEventAccess) As BoundNode
Dim receiverOpt As BoundExpression = DirectCast(Me.Visit(node.ReceiverOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOpt, node.EventSymbol, type)
End Function
Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode
Dim statements As ImmutableArray(Of BoundStatement) = Me.VisitList(node.Statements)
Return node.Update(node.StatementListSyntax, node.Locals, statements)
End Function
Public Overrides Function VisitStateMachineScope(node As BoundStateMachineScope) As BoundNode
Dim statement As BoundStatement = DirectCast(Me.Visit(node.Statement), BoundStatement)
Return node.Update(node.Fields, statement)
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode
Dim declarationInitializerOpt As BoundExpression = DirectCast(Me.Visit(node.DeclarationInitializerOpt), BoundExpression)
Dim identifierInitializerOpt As BoundArrayCreation = DirectCast(Me.Visit(node.IdentifierInitializerOpt), BoundArrayCreation)
Return node.Update(node.LocalSymbol, declarationInitializerOpt, identifierInitializerOpt, node.InitializedByAsNew)
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations) As BoundNode
Dim localDeclarations As ImmutableArray(Of BoundLocalDeclaration) = Me.VisitList(node.LocalDeclarations)
Dim initializer As BoundExpression = DirectCast(Me.Visit(node.Initializer), BoundExpression)
Return node.Update(localDeclarations, initializer, node.Binder)
End Function
Public Overrides Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Dim localDeclarations As ImmutableArray(Of BoundLocalDeclarationBase) = Me.VisitList(node.LocalDeclarations)
Dim initializerOpt As BoundExpression = DirectCast(Me.Visit(node.InitializerOpt), BoundExpression)
Return node.Update(localDeclarations, initializerOpt)
End Function
Public Overrides Function VisitInitializer(node As BoundInitializer) As BoundNode
Return node
End Function
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer) As BoundNode
Dim memberAccessExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.MemberAccessExpressionOpt), BoundExpression)
Dim initialValue As BoundExpression = DirectCast(Me.Visit(node.InitialValue), BoundExpression)
Return node.Update(node.InitializedFields, memberAccessExpressionOpt, initialValue, node.BinderOpt)
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer) As BoundNode
Dim memberAccessExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.MemberAccessExpressionOpt), BoundExpression)
Dim initialValue As BoundExpression = DirectCast(Me.Visit(node.InitialValue), BoundExpression)
Return node.Update(node.InitializedProperties, memberAccessExpressionOpt, initialValue, node.BinderOpt)
End Function
Public Overrides Function VisitParameterEqualsValue(node As BoundParameterEqualsValue) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Return node.Update(node.Parameter, value)
End Function
Public Overrides Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer) As BoundNode
Dim statement As BoundStatement = DirectCast(Me.Visit(node.Statement), BoundStatement)
Return node.Update(statement)
End Function
Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode
Dim sideEffects As ImmutableArray(Of BoundExpression) = Me.VisitList(node.SideEffects)
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Locals, sideEffects, valueOpt, type)
End Function
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Return node.Update(expression)
End Function
Public Overrides Function VisitIfStatement(node As BoundIfStatement) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Dim consequence As BoundStatement = DirectCast(Me.Visit(node.Consequence), BoundStatement)
Dim alternativeOpt As BoundStatement = DirectCast(Me.Visit(node.AlternativeOpt), BoundStatement)
Return node.Update(condition, consequence, alternativeOpt)
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode
Dim expressionStatement As BoundExpressionStatement = DirectCast(Me.Visit(node.ExpressionStatement), BoundExpressionStatement)
Dim exprPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.ExprPlaceholderOpt), BoundRValuePlaceholder)
Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = Me.VisitList(node.CaseBlocks)
Return node.Update(expressionStatement, exprPlaceholderOpt, caseBlocks, node.RecommendSwitchTable, node.ExitLabel)
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock) As BoundNode
Dim caseStatement As BoundCaseStatement = DirectCast(Me.Visit(node.CaseStatement), BoundCaseStatement)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(caseStatement, body)
End Function
Public Overrides Function VisitCaseStatement(node As BoundCaseStatement) As BoundNode
Dim caseClauses As ImmutableArray(Of BoundCaseClause) = Me.VisitList(node.CaseClauses)
Dim conditionOpt As BoundExpression = DirectCast(Me.Visit(node.ConditionOpt), BoundExpression)
Return node.Update(caseClauses, conditionOpt)
End Function
Public Overrides Function VisitSimpleCaseClause(node As BoundSimpleCaseClause) As BoundNode
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim conditionOpt As BoundExpression = DirectCast(Me.Visit(node.ConditionOpt), BoundExpression)
Return node.Update(valueOpt, conditionOpt)
End Function
Public Overrides Function VisitRangeCaseClause(node As BoundRangeCaseClause) As BoundNode
Dim lowerBoundOpt As BoundExpression = DirectCast(Me.Visit(node.LowerBoundOpt), BoundExpression)
Dim upperBoundOpt As BoundExpression = DirectCast(Me.Visit(node.UpperBoundOpt), BoundExpression)
Dim lowerBoundConditionOpt As BoundExpression = DirectCast(Me.Visit(node.LowerBoundConditionOpt), BoundExpression)
Dim upperBoundConditionOpt As BoundExpression = DirectCast(Me.Visit(node.UpperBoundConditionOpt), BoundExpression)
Return node.Update(lowerBoundOpt, upperBoundOpt, lowerBoundConditionOpt, upperBoundConditionOpt)
End Function
Public Overrides Function VisitRelationalCaseClause(node As BoundRelationalCaseClause) As BoundNode
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim conditionOpt As BoundExpression = DirectCast(Me.Visit(node.ConditionOpt), BoundExpression)
Return node.Update(node.OperatorKind, valueOpt, conditionOpt)
End Function
Public Overrides Function VisitDoLoopStatement(node As BoundDoLoopStatement) As BoundNode
Dim topConditionOpt As BoundExpression = DirectCast(Me.Visit(node.TopConditionOpt), BoundExpression)
Dim bottomConditionOpt As BoundExpression = DirectCast(Me.Visit(node.BottomConditionOpt), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Return node.Update(topConditionOpt, bottomConditionOpt, node.TopConditionIsUntil, node.BottomConditionIsUntil, body, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Return node.Update(condition, body, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators) As BoundNode
Dim leftOperandPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.LeftOperandPlaceholder), BoundRValuePlaceholder)
Dim rightOperandPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.RightOperandPlaceholder), BoundRValuePlaceholder)
Dim addition As BoundUserDefinedBinaryOperator = DirectCast(Me.Visit(node.Addition), BoundUserDefinedBinaryOperator)
Dim subtraction As BoundUserDefinedBinaryOperator = DirectCast(Me.Visit(node.Subtraction), BoundUserDefinedBinaryOperator)
Dim lessThanOrEqual As BoundExpression = DirectCast(Me.Visit(node.LessThanOrEqual), BoundExpression)
Dim greaterThanOrEqual As BoundExpression = DirectCast(Me.Visit(node.GreaterThanOrEqual), BoundExpression)
Return node.Update(leftOperandPlaceholder, rightOperandPlaceholder, addition, subtraction, lessThanOrEqual, greaterThanOrEqual)
End Function
Public Overrides Function VisitForToStatement(node As BoundForToStatement) As BoundNode
Dim initialValue As BoundExpression = DirectCast(Me.Visit(node.InitialValue), BoundExpression)
Dim limitValue As BoundExpression = DirectCast(Me.Visit(node.LimitValue), BoundExpression)
Dim stepValue As BoundExpression = DirectCast(Me.Visit(node.StepValue), BoundExpression)
Dim operatorsOpt As BoundForToUserDefinedOperators = DirectCast(Me.Visit(node.OperatorsOpt), BoundForToUserDefinedOperators)
Dim controlVariable As BoundExpression = DirectCast(Me.Visit(node.ControlVariable), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Dim nextVariablesOpt As ImmutableArray(Of BoundExpression) = Me.VisitList(node.NextVariablesOpt)
Return node.Update(initialValue, limitValue, stepValue, node.Checked, operatorsOpt, node.DeclaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
Dim collection As BoundExpression = DirectCast(Me.Visit(node.Collection), BoundExpression)
Dim controlVariable As BoundExpression = DirectCast(Me.Visit(node.ControlVariable), BoundExpression)
Dim body As BoundStatement = DirectCast(Me.Visit(node.Body), BoundStatement)
Dim nextVariablesOpt As ImmutableArray(Of BoundExpression) = Me.VisitList(node.NextVariablesOpt)
Return node.Update(collection, node.EnumeratorInfo, node.DeclaredOrInferredLocalOpt, controlVariable, body, nextVariablesOpt, node.ContinueLabel, node.ExitLabel)
End Function
Public Overrides Function VisitExitStatement(node As BoundExitStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitContinueStatement(node As BoundContinueStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Dim tryBlock As BoundBlock = DirectCast(Me.Visit(node.TryBlock), BoundBlock)
Dim catchBlocks As ImmutableArray(Of BoundCatchBlock) = Me.VisitList(node.CatchBlocks)
Dim finallyBlockOpt As BoundBlock = DirectCast(Me.Visit(node.FinallyBlockOpt), BoundBlock)
Return node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.ExitLabelOpt)
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Dim exceptionSourceOpt As BoundExpression = DirectCast(Me.Visit(node.ExceptionSourceOpt), BoundExpression)
Dim errorLineNumberOpt As BoundExpression = DirectCast(Me.Visit(node.ErrorLineNumberOpt), BoundExpression)
Dim exceptionFilterOpt As BoundExpression = DirectCast(Me.Visit(node.ExceptionFilterOpt), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(node.LocalOpt, exceptionSourceOpt, errorLineNumberOpt, exceptionFilterOpt, body, node.IsSynthesizedAsyncCatchAll)
End Function
Public Overrides Function VisitLiteral(node As BoundLiteral) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Value, type)
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.SourceType, type)
End Function
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(type)
End Function
Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LocalSymbol, node.IsLValue, type)
End Function
Public Overrides Function VisitPseudoVariable(node As BoundPseudoVariable) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LocalSymbol, node.IsLValue, node.EmitExpressions, type)
End Function
Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.ParameterSymbol, node.IsLValue, node.SuppressVirtualCalls, type)
End Function
Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.IsOut, type)
End Function
Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode
Dim originalArgument As BoundExpression = DirectCast(Me.Visit(node.OriginalArgument), BoundExpression)
Dim inConversion As BoundExpression = DirectCast(Me.Visit(node.InConversion), BoundExpression)
Dim inPlaceholder As BoundByRefArgumentPlaceholder = DirectCast(Me.Visit(node.InPlaceholder), BoundByRefArgumentPlaceholder)
Dim outConversion As BoundExpression = DirectCast(Me.Visit(node.OutConversion), BoundExpression)
Dim outPlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.OutPlaceholder), BoundRValuePlaceholder)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(originalArgument, inConversion, inPlaceholder, outConversion, outPlaceholder, type)
End Function
Public Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture) As BoundNode
Dim originalArgument As BoundExpression = DirectCast(Me.Visit(node.OriginalArgument), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(originalArgument, node.LocalSymbol, type)
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitLabel(node As BoundLabel) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Label, type)
End Function
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement) As BoundNode
Dim labelExpressionOpt As BoundLabel = DirectCast(Me.Visit(node.LabelExpressionOpt), BoundLabel)
Return node.Update(node.Label, labelExpressionOpt)
End Function
Public Overrides Function VisitStatementList(node As BoundStatementList) As BoundNode
Dim statements As ImmutableArray(Of BoundStatement) = Me.VisitList(node.Statements)
Return node.Update(statements)
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto) As BoundNode
Dim condition As BoundExpression = DirectCast(Me.Visit(node.Condition), BoundExpression)
Return node.Update(condition, node.JumpIfTrue, node.Label)
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement) As BoundNode
Dim originalExpression As BoundExpression = DirectCast(Me.Visit(node.OriginalExpression), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(originalExpression, body, node.Binder)
End Function
Public Overrides Function VisitUnboundLambda(node As UnboundLambda) As BoundNode
Dim returnType as TypeSymbol = Me.VisitType(node.ReturnType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.Flags, node.Parameters, returnType, node.BindingCache)
End Function
Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LambdaSymbol, body, node.Diagnostics, node.LambdaBinderOpt, node.DelegateRelaxation, node.MethodConversionKind)
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression) As BoundNode
Dim lastOperator As BoundQueryClauseBase = DirectCast(Me.Visit(node.LastOperator), BoundQueryClauseBase)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(lastOperator, type)
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion) As BoundNode
Dim conversionCall As BoundCall = DirectCast(Me.Visit(node.ConversionCall), BoundCall)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(conversionCall, type)
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource) As BoundNode
Dim source As BoundQueryPart = DirectCast(Me.Visit(node.Source), BoundQueryPart)
Dim compoundVariableType as TypeSymbol = Me.VisitType(node.CompoundVariableType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(source, node.RangeVariableOpt, node.RangeVariables, compoundVariableType, node.Binders, type)
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim compoundVariableType as TypeSymbol = Me.VisitType(node.CompoundVariableType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingExpression, node.RangeVariables, compoundVariableType, node.Binders, type)
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering) As BoundNode
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(underlyingExpression, type)
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.LambdaSymbol, node.RangeVariables, expression, node.ExprIsOperandOfConditionalBranch)
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.RangeVariable, value, type)
End Function
Public Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Binder, node.Parameters, node.Compilation)
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause) As BoundNode
Dim capturedGroupOpt As BoundQueryClauseBase = DirectCast(Me.Visit(node.CapturedGroupOpt), BoundQueryClauseBase)
Dim groupPlaceholderOpt As BoundRValuePlaceholder = DirectCast(Me.Visit(node.GroupPlaceholderOpt), BoundRValuePlaceholder)
Dim underlyingExpression As BoundExpression = DirectCast(Me.Visit(node.UnderlyingExpression), BoundExpression)
Dim compoundVariableType as TypeSymbol = Me.VisitType(node.CompoundVariableType)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(capturedGroupOpt, groupPlaceholderOpt, underlyingExpression, node.RangeVariables, compoundVariableType, node.Binders, type)
End Function
Public Overrides Function VisitGroupAggregation(node As BoundGroupAggregation) As BoundNode
Dim group As BoundExpression = DirectCast(Me.Visit(node.Group), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(group, type)
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.RangeVariable, type)
End Function
Public Overrides Function VisitAddHandlerStatement(node As BoundAddHandlerStatement) As BoundNode
Dim eventAccess As BoundExpression = DirectCast(Me.Visit(node.EventAccess), BoundExpression)
Dim handler As BoundExpression = DirectCast(Me.Visit(node.Handler), BoundExpression)
Return node.Update(eventAccess, handler)
End Function
Public Overrides Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement) As BoundNode
Dim eventAccess As BoundExpression = DirectCast(Me.Visit(node.EventAccess), BoundExpression)
Dim handler As BoundExpression = DirectCast(Me.Visit(node.Handler), BoundExpression)
Return node.Update(eventAccess, handler)
End Function
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode
Dim eventInvocation As BoundExpression = DirectCast(Me.Visit(node.EventInvocation), BoundExpression)
Return node.Update(node.EventSymbol, eventInvocation)
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement) As BoundNode
Dim resourceList As ImmutableArray(Of BoundLocalDeclarationBase) = Me.VisitList(node.ResourceList)
Dim resourceExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.ResourceExpressionOpt), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(resourceList, resourceExpressionOpt, body, node.UsingInfo, node.Locals)
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode
Dim lockExpression As BoundExpression = DirectCast(Me.Visit(node.LockExpression), BoundExpression)
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(lockExpression, body)
End Function
Public Overrides Function VisitXmlName(node As BoundXmlName) As BoundNode
Dim xmlNamespace As BoundExpression = DirectCast(Me.Visit(node.XmlNamespace), BoundExpression)
Dim localName As BoundExpression = DirectCast(Me.Visit(node.LocalName), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(xmlNamespace, localName, objectCreation, type)
End Function
Public Overrides Function VisitXmlNamespace(node As BoundXmlNamespace) As BoundNode
Dim xmlNamespace As BoundExpression = DirectCast(Me.Visit(node.XmlNamespace), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(xmlNamespace, objectCreation, type)
End Function
Public Overrides Function VisitXmlDocument(node As BoundXmlDocument) As BoundNode
Dim declaration As BoundExpression = DirectCast(Me.Visit(node.Declaration), BoundExpression)
Dim childNodes As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ChildNodes)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(declaration, childNodes, node.RewriterInfo, type)
End Function
Public Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration) As BoundNode
Dim version As BoundExpression = DirectCast(Me.Visit(node.Version), BoundExpression)
Dim encoding As BoundExpression = DirectCast(Me.Visit(node.Encoding), BoundExpression)
Dim standalone As BoundExpression = DirectCast(Me.Visit(node.Standalone), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(version, encoding, standalone, objectCreation, type)
End Function
Public Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction) As BoundNode
Dim target As BoundExpression = DirectCast(Me.Visit(node.Target), BoundExpression)
Dim data As BoundExpression = DirectCast(Me.Visit(node.Data), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(target, data, objectCreation, type)
End Function
Public Overrides Function VisitXmlComment(node As BoundXmlComment) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(value, objectCreation, type)
End Function
Public Overrides Function VisitXmlAttribute(node As BoundXmlAttribute) As BoundNode
Dim name As BoundExpression = DirectCast(Me.Visit(node.Name), BoundExpression)
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(name, value, node.MatchesImport, objectCreation, type)
End Function
Public Overrides Function VisitXmlElement(node As BoundXmlElement) As BoundNode
Dim argument As BoundExpression = DirectCast(Me.Visit(node.Argument), BoundExpression)
Dim childNodes As ImmutableArray(Of BoundExpression) = Me.VisitList(node.ChildNodes)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(argument, childNodes, node.RewriterInfo, type)
End Function
Public Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess) As BoundNode
Dim memberAccess As BoundExpression = DirectCast(Me.Visit(node.MemberAccess), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(memberAccess, type)
End Function
Public Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitXmlCData(node As BoundXmlCData) As BoundNode
Dim value As BoundLiteral = DirectCast(Me.Visit(node.Value), BoundLiteral)
Dim objectCreation As BoundExpression = node.ObjectCreation
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(value, objectCreation, type)
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement) As BoundNode
Dim labelExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.LabelExpressionOpt), BoundExpression)
Return node.Update(node.ResumeKind, node.LabelOpt, labelExpressionOpt)
End Function
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement) As BoundNode
Dim labelExpressionOpt As BoundExpression = DirectCast(Me.Visit(node.LabelExpressionOpt), BoundExpression)
Return node.Update(node.OnErrorKind, node.LabelOpt, labelExpressionOpt)
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement) As BoundNode
Dim body As BoundBlock = DirectCast(Me.Visit(node.Body), BoundBlock)
Return node.Update(node.ContainsOnError, node.ContainsResume, node.ResumeWithoutLabelOpt, node.TrackLineNumber, body)
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter) As BoundNode
Dim activeHandlerLocal As BoundLocal = DirectCast(Me.Visit(node.ActiveHandlerLocal), BoundLocal)
Dim resumeTargetLocal As BoundLocal = DirectCast(Me.Visit(node.ResumeTargetLocal), BoundLocal)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(activeHandlerLocal, resumeTargetLocal, type)
End Function
Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch) As BoundNode
Dim value As BoundExpression = DirectCast(Me.Visit(node.Value), BoundExpression)
Dim jumps As ImmutableArray(Of BoundGotoStatement) = Me.VisitList(node.Jumps)
Return node.Update(value, jumps)
End Function
Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch) As BoundNode
Dim resumeTargetTemporary As BoundLocal = DirectCast(Me.Visit(node.ResumeTargetTemporary), BoundLocal)
Dim resumeLabel As BoundLabelStatement = DirectCast(Me.Visit(node.ResumeLabel), BoundLabelStatement)
Dim resumeNextLabel As BoundLabelStatement = DirectCast(Me.Visit(node.ResumeNextLabel), BoundLabelStatement)
Dim jumps As ImmutableArray(Of BoundGotoStatement) = Me.VisitList(node.Jumps)
Return node.Update(resumeTargetTemporary, resumeLabel, resumeNextLabel, jumps)
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode
Dim operand As BoundExpression = DirectCast(Me.Visit(node.Operand), BoundExpression)
Dim awaitableInstancePlaceholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.AwaitableInstancePlaceholder), BoundRValuePlaceholder)
Dim getAwaiter As BoundExpression = DirectCast(Me.Visit(node.GetAwaiter), BoundExpression)
Dim awaiterInstancePlaceholder As BoundLValuePlaceholder = DirectCast(Me.Visit(node.AwaiterInstancePlaceholder), BoundLValuePlaceholder)
Dim isCompleted As BoundExpression = DirectCast(Me.Visit(node.IsCompleted), BoundExpression)
Dim getResult As BoundExpression = DirectCast(Me.Visit(node.GetResult), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(operand, awaitableInstancePlaceholder, getAwaiter, awaiterInstancePlaceholder, isCompleted, getResult, type)
End Function
Public Overrides Function VisitSpillSequence(node As BoundSpillSequence) As BoundNode
Dim statements As ImmutableArray(Of BoundStatement) = Me.VisitList(node.Statements)
Dim valueOpt As BoundExpression = DirectCast(Me.Visit(node.ValueOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.Locals, node.SpillFields, statements, valueOpt, type)
End Function
Public Overrides Function VisitStopStatement(node As BoundStopStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitEndStatement(node As BoundEndStatement) As BoundNode
Return node
End Function
Public Overrides Function VisitMidResult(node As BoundMidResult) As BoundNode
Dim original As BoundExpression = DirectCast(Me.Visit(node.Original), BoundExpression)
Dim start As BoundExpression = DirectCast(Me.Visit(node.Start), BoundExpression)
Dim lengthOpt As BoundExpression = DirectCast(Me.Visit(node.LengthOpt), BoundExpression)
Dim source As BoundExpression = DirectCast(Me.Visit(node.Source), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(original, start, lengthOpt, source, type)
End Function
Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode
Dim receiver As BoundExpression = DirectCast(Me.Visit(node.Receiver), BoundExpression)
Dim placeholder As BoundRValuePlaceholder = DirectCast(Me.Visit(node.Placeholder), BoundRValuePlaceholder)
Dim accessExpression As BoundExpression = DirectCast(Me.Visit(node.AccessExpression), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiver, placeholder, accessExpression, type)
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder) As BoundNode
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(node.PlaceholderId, type)
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess) As BoundNode
Dim receiverOrCondition As BoundExpression = DirectCast(Me.Visit(node.ReceiverOrCondition), BoundExpression)
Dim whenNotNull As BoundExpression = DirectCast(Me.Visit(node.WhenNotNull), BoundExpression)
Dim whenNullOpt As BoundExpression = DirectCast(Me.Visit(node.WhenNullOpt), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(receiverOrCondition, node.CaptureReceiver, node.PlaceholderId, whenNotNull, whenNullOpt, type)
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver) As BoundNode
Dim valueTypeReceiver As BoundExpression = DirectCast(Me.Visit(node.ValueTypeReceiver), BoundExpression)
Dim referenceTypeReceiver As BoundExpression = DirectCast(Me.Visit(node.ReferenceTypeReceiver), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(valueTypeReceiver, referenceTypeReceiver, type)
End Function
Public Overrides Function VisitNameOfOperator(node As BoundNameOfOperator) As BoundNode
Dim argument As BoundExpression = DirectCast(Me.Visit(node.Argument), BoundExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(argument, node.ConstantValueOpt, type)
End Function
Public Overrides Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression) As BoundNode
Dim expression As BoundTypeExpression = DirectCast(Me.Visit(node.Expression), BoundTypeExpression)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(expression, type)
End Function
Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode
Dim contents As ImmutableArray(Of BoundNode) = Me.VisitList(node.Contents)
Dim type as TypeSymbol = Me.VisitType(node.Type)
Return node.Update(contents, node.Binder, type)
End Function
Public Overrides Function VisitInterpolation(node As BoundInterpolation) As BoundNode
Dim expression As BoundExpression = DirectCast(Me.Visit(node.Expression), BoundExpression)
Dim alignmentOpt As BoundExpression = DirectCast(Me.Visit(node.AlignmentOpt), BoundExpression)
Dim formatStringOpt As BoundLiteral = DirectCast(Me.Visit(node.FormatStringOpt), BoundLiteral)
Return node.Update(expression, alignmentOpt, formatStringOpt)
End Function
End Class
Friend NotInheritable Class BoundTreeDumperNodeProducer
Inherits BoundTreeVisitor(Of Object, TreeDumperNode)
Private Sub New()
End Sub
Public Shared Function MakeTree(node As BoundNode) As TreeDumperNode
Return (New BoundTreeDumperNodeProducer()).Visit(node, Nothing)
End Function
Public Overrides Function VisitTypeArguments(node As BoundTypeArguments, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeArguments", Nothing, New TreeDumperNode() {
New TreeDumperNode("arguments", node.Arguments, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitOmittedArgument(node As BoundOmittedArgument, arg As Object) As TreeDumperNode
Return New TreeDumperNode("omittedArgument", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLValueToRValueWrapper(node As BoundLValueToRValueWrapper, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lValueToRValueWrapper", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingLValue", Nothing, new TreeDumperNode() {Visit(node.UnderlyingLValue, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("withLValueExpressionPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitWithRValueExpressionPlaceholder(node As BoundWithRValueExpressionPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("withRValueExpressionPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rValuePlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lValuePlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitDup(node As BoundDup, arg As Object) As TreeDumperNode
Return New TreeDumperNode("dup", Nothing, New TreeDumperNode() {
New TreeDumperNode("isReference", node.IsReference, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBadExpression(node As BoundBadExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("badExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("symbols", node.Symbols, Nothing),
New TreeDumperNode("childBoundNodes", Nothing, From x In node.ChildBoundNodes Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBadStatement(node As BoundBadStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("badStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("childBoundNodes", Nothing, From x In node.ChildBoundNodes Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitParenthesized(node As BoundParenthesized, arg As Object) As TreeDumperNode
Return New TreeDumperNode("parenthesized", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBadVariable(node As BoundBadVariable, arg As Object) As TreeDumperNode
Return New TreeDumperNode("badVariable", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayAccess(node As BoundArrayAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("indices", Nothing, From x In node.Indices Select Visit(x, Nothing)),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayLength(node As BoundArrayLength, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayLength", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGetType(node As BoundGetType, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[getType]", Nothing, New TreeDumperNode() {
New TreeDumperNode("sourceType", Nothing, new TreeDumperNode() {Visit(node.SourceType, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitFieldInfo(node As BoundFieldInfo, arg As Object) As TreeDumperNode
Return New TreeDumperNode("fieldInfo", Nothing, New TreeDumperNode() {
New TreeDumperNode("field", node.Field, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMethodInfo(node As BoundMethodInfo, arg As Object) As TreeDumperNode
Return New TreeDumperNode("methodInfo", Nothing, New TreeDumperNode() {
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeExpression(node As BoundTypeExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("unevaluatedReceiverOpt", Nothing, new TreeDumperNode() {Visit(node.UnevaluatedReceiverOpt, Nothing)}),
New TreeDumperNode("aliasOpt", node.AliasOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeOrValueExpression(node As BoundTypeOrValueExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeOrValueExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("data", node.Data, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNamespaceExpression(node As BoundNamespaceExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("namespaceExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("unevaluatedReceiverOpt", Nothing, new TreeDumperNode() {Visit(node.UnevaluatedReceiverOpt, Nothing)}),
New TreeDumperNode("aliasOpt", node.AliasOpt, Nothing),
New TreeDumperNode("namespaceSymbol", node.NamespaceSymbol, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMethodDefIndex(node As BoundMethodDefIndex, arg As Object) As TreeDumperNode
Return New TreeDumperNode("methodDefIndex", Nothing, New TreeDumperNode() {
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMaximumMethodDefIndex(node As BoundMaximumMethodDefIndex, arg As Object) As TreeDumperNode
Return New TreeDumperNode("maximumMethodDefIndex", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitInstrumentationPayloadRoot(node As BoundInstrumentationPayloadRoot, arg As Object) As TreeDumperNode
Return New TreeDumperNode("instrumentationPayloadRoot", Nothing, New TreeDumperNode() {
New TreeDumperNode("analysisKind", node.AnalysisKind, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitModuleVersionId(node As BoundModuleVersionId, arg As Object) As TreeDumperNode
Return New TreeDumperNode("moduleVersionId", Nothing, New TreeDumperNode() {
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitModuleVersionIdString(node As BoundModuleVersionIdString, arg As Object) As TreeDumperNode
Return New TreeDumperNode("moduleVersionIdString", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSourceDocumentIndex(node As BoundSourceDocumentIndex, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sourceDocumentIndex", Nothing, New TreeDumperNode() {
New TreeDumperNode("document", node.Document, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUnaryOperator(node As BoundUnaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedUnaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNullableIsTrueOperator(node As BoundNullableIsTrueOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("nullableIsTrueOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBinaryOperator(node As BoundBinaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("binaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("left", Nothing, new TreeDumperNode() {Visit(node.Left, Nothing)}),
New TreeDumperNode("right", Nothing, new TreeDumperNode() {Visit(node.Right, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedBinaryOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedShortCircuitingOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("leftOperand", Nothing, new TreeDumperNode() {Visit(node.LeftOperand, Nothing)}),
New TreeDumperNode("leftOperandPlaceholder", Nothing, new TreeDumperNode() {Visit(node.LeftOperandPlaceholder, Nothing)}),
New TreeDumperNode("leftTest", Nothing, new TreeDumperNode() {Visit(node.LeftTest, Nothing)}),
New TreeDumperNode("bitwiseOperator", Nothing, new TreeDumperNode() {Visit(node.BitwiseOperator, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitCompoundAssignmentTargetPlaceholder(node As BoundCompoundAssignmentTargetPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("compoundAssignmentTargetPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("assignmentOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("left", Nothing, new TreeDumperNode() {Visit(node.Left, Nothing)}),
New TreeDumperNode("leftOnTheRightOpt", Nothing, new TreeDumperNode() {Visit(node.LeftOnTheRightOpt, Nothing)}),
New TreeDumperNode("right", Nothing, new TreeDumperNode() {Visit(node.Right, Nothing)}),
New TreeDumperNode("suppressObjectClone", node.SuppressObjectClone, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitReferenceAssignment(node As BoundReferenceAssignment, arg As Object) As TreeDumperNode
Return New TreeDumperNode("referenceAssignment", Nothing, New TreeDumperNode() {
New TreeDumperNode("byRefLocal", Nothing, new TreeDumperNode() {Visit(node.ByRefLocal, Nothing)}),
New TreeDumperNode("lValue", Nothing, new TreeDumperNode() {Visit(node.LValue, Nothing)}),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAddressOfOperator(node As BoundAddressOfOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("addressOfOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("withDependencies", node.WithDependencies, Nothing),
New TreeDumperNode("methodGroup", Nothing, new TreeDumperNode() {Visit(node.MethodGroup, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTernaryConditionalExpression(node As BoundTernaryConditionalExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("ternaryConditionalExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("whenTrue", Nothing, new TreeDumperNode() {Visit(node.WhenTrue, Nothing)}),
New TreeDumperNode("whenFalse", Nothing, new TreeDumperNode() {Visit(node.WhenFalse, Nothing)}),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBinaryConditionalExpression(node As BoundBinaryConditionalExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("binaryConditionalExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("testExpression", Nothing, new TreeDumperNode() {Visit(node.TestExpression, Nothing)}),
New TreeDumperNode("convertedTestExpression", Nothing, new TreeDumperNode() {Visit(node.ConvertedTestExpression, Nothing)}),
New TreeDumperNode("testExpressionPlaceholder", Nothing, new TreeDumperNode() {Visit(node.TestExpressionPlaceholder, Nothing)}),
New TreeDumperNode("elseExpression", Nothing, new TreeDumperNode() {Visit(node.ElseExpression, Nothing)}),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConversion(node As BoundConversion, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conversion", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("conversionKind", node.ConversionKind, Nothing),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("explicitCastInCode", node.ExplicitCastInCode, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("extendedInfoOpt", Nothing, new TreeDumperNode() {Visit(node.ExtendedInfoOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRelaxationLambda(node As BoundRelaxationLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("relaxationLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("lambda", Nothing, new TreeDumperNode() {Visit(node.Lambda, Nothing)}),
New TreeDumperNode("receiverPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverPlaceholderOpt, Nothing)})
})
End Function
Public Overrides Function VisitConvertedTupleElements(node As BoundConvertedTupleElements, arg As Object) As TreeDumperNode
Return New TreeDumperNode("convertedTupleElements", Nothing, New TreeDumperNode() {
New TreeDumperNode("elementPlaceholders", Nothing, From x In node.ElementPlaceholders Select Visit(x, Nothing)),
New TreeDumperNode("convertedElements", Nothing, From x In node.ConvertedElements Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitUserDefinedConversion(node As BoundUserDefinedConversion, arg As Object) As TreeDumperNode
Return New TreeDumperNode("userDefinedConversion", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("inOutConversionFlags", node.InOutConversionFlags, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitDirectCast(node As BoundDirectCast, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[directCast]", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("conversionKind", node.ConversionKind, Nothing),
New TreeDumperNode("suppressVirtualCalls", node.SuppressVirtualCalls, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("relaxationLambdaOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationLambdaOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTryCast(node As BoundTryCast, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[tryCast]", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("conversionKind", node.ConversionKind, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("relaxationLambdaOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationLambdaOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeOf(node As BoundTypeOf, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[typeOf]", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("isTypeOfIsNotExpression", node.IsTypeOfIsNotExpression, Nothing),
New TreeDumperNode("targetType", node.TargetType, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSequencePoint(node As BoundSequencePoint, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequencePoint", Nothing, New TreeDumperNode() {
New TreeDumperNode("statementOpt", Nothing, new TreeDumperNode() {Visit(node.StatementOpt, Nothing)})
})
End Function
Public Overrides Function VisitSequencePointExpression(node As BoundSequencePointExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequencePointExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSequencePointWithSpan(node As BoundSequencePointWithSpan, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequencePointWithSpan", Nothing, New TreeDumperNode() {
New TreeDumperNode("statementOpt", Nothing, new TreeDumperNode() {Visit(node.StatementOpt, Nothing)}),
New TreeDumperNode("span", node.Span, Nothing)
})
End Function
Public Overrides Function VisitNoOpStatement(node As BoundNoOpStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("noOpStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("flavor", node.Flavor, Nothing)
})
End Function
Public Overrides Function VisitMethodGroup(node As BoundMethodGroup, arg As Object) As TreeDumperNode
Return New TreeDumperNode("methodGroup", Nothing, New TreeDumperNode() {
New TreeDumperNode("typeArgumentsOpt", Nothing, new TreeDumperNode() {Visit(node.TypeArgumentsOpt, Nothing)}),
New TreeDumperNode("methods", node.Methods, Nothing),
New TreeDumperNode("pendingExtensionMethodsOpt", node.PendingExtensionMethodsOpt, Nothing),
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("qualificationKind", node.QualificationKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPropertyGroup(node As BoundPropertyGroup, arg As Object) As TreeDumperNode
Return New TreeDumperNode("propertyGroup", Nothing, New TreeDumperNode() {
New TreeDumperNode("properties", node.Properties, Nothing),
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("qualificationKind", node.QualificationKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("returnStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expressionOpt", Nothing, new TreeDumperNode() {Visit(node.ExpressionOpt, Nothing)}),
New TreeDumperNode("functionLocalOpt", node.FunctionLocalOpt, Nothing),
New TreeDumperNode("exitLabelOpt", node.ExitLabelOpt, Nothing)
})
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("yieldStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)})
})
End Function
Public Overrides Function VisitThrowStatement(node As BoundThrowStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("throwStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expressionOpt", Nothing, new TreeDumperNode() {Visit(node.ExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitRedimStatement(node As BoundRedimStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("redimStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("clauses", Nothing, From x In node.Clauses Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitRedimClause(node As BoundRedimClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("redimClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("indices", Nothing, From x In node.Indices Select Visit(x, Nothing)),
New TreeDumperNode("arrayTypeOpt", node.ArrayTypeOpt, Nothing),
New TreeDumperNode("preserve", node.Preserve, Nothing)
})
End Function
Public Overrides Function VisitEraseStatement(node As BoundEraseStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("eraseStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("clauses", Nothing, From x In node.Clauses Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitCall(node As BoundCall, arg As Object) As TreeDumperNode
Return New TreeDumperNode("[call]", Nothing, New TreeDumperNode() {
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("methodGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodGroupOpt, Nothing)}),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("defaultArguments", node.DefaultArguments, Nothing),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("suppressObjectClone", node.SuppressObjectClone, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAttribute(node As BoundAttribute, arg As Object) As TreeDumperNode
Return New TreeDumperNode("attribute", Nothing, New TreeDumperNode() {
New TreeDumperNode("constructor", node.Constructor, Nothing),
New TreeDumperNode("constructorArguments", Nothing, From x In node.ConstructorArguments Select Visit(x, Nothing)),
New TreeDumperNode("namedArguments", Nothing, From x In node.NamedArguments Select Visit(x, Nothing)),
New TreeDumperNode("resultKind", node.ResultKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateMemberAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("nameOpt", node.NameOpt, Nothing),
New TreeDumperNode("containerTypeOpt", node.ContainerTypeOpt, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("typeArgumentsOpt", Nothing, new TreeDumperNode() {Visit(node.TypeArgumentsOpt, Nothing)}),
New TreeDumperNode("accessKind", node.AccessKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateInvocation(node As BoundLateInvocation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateInvocation", Nothing, New TreeDumperNode() {
New TreeDumperNode("member", Nothing, new TreeDumperNode() {Visit(node.Member, Nothing)}),
New TreeDumperNode("argumentsOpt", Nothing, From x In node.ArgumentsOpt Select Visit(x, Nothing)),
New TreeDumperNode("argumentNamesOpt", node.ArgumentNamesOpt, Nothing),
New TreeDumperNode("accessKind", node.AccessKind, Nothing),
New TreeDumperNode("methodOrPropertyGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodOrPropertyGroupOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateAddressOfOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("memberAccess", Nothing, new TreeDumperNode() {Visit(node.MemberAccess, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("tupleLiteral", Nothing, New TreeDumperNode() {
New TreeDumperNode("inferredType", node.InferredType, Nothing),
New TreeDumperNode("argumentNamesOpt", node.ArgumentNamesOpt, Nothing),
New TreeDumperNode("inferredNamesOpt", node.InferredNamesOpt, Nothing),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("convertedTupleLiteral", Nothing, New TreeDumperNode() {
New TreeDumperNode("naturalTypeOpt", node.NaturalTypeOpt, Nothing),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("objectCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("constructorOpt", node.ConstructorOpt, Nothing),
New TreeDumperNode("methodGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodGroupOpt, Nothing)}),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("defaultArguments", node.DefaultArguments, Nothing),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("noPiaObjectCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("guidString", node.GuidString, Nothing),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("anonymousTypeCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("binderOpt", node.BinderOpt, Nothing),
New TreeDumperNode("declarations", Nothing, From x In node.Declarations Select Visit(x, Nothing)),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("anonymousTypePropertyAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("propertyIndex", node.PropertyIndex, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAnonymousTypeFieldInitializer(node As BoundAnonymousTypeFieldInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("anonymousTypeFieldInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("objectInitializerExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("createTemporaryLocalForInitialization", node.CreateTemporaryLocalForInitialization, Nothing),
New TreeDumperNode("placeholderOpt", Nothing, new TreeDumperNode() {Visit(node.PlaceholderOpt, Nothing)}),
New TreeDumperNode("initializers", Nothing, From x In node.Initializers Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitCollectionInitializerExpression(node As BoundCollectionInitializerExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("collectionInitializerExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("placeholderOpt", Nothing, new TreeDumperNode() {Visit(node.PlaceholderOpt, Nothing)}),
New TreeDumperNode("initializers", Nothing, From x In node.Initializers Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNewT(node As BoundNewT, arg As Object) As TreeDumperNode
Return New TreeDumperNode("newT", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("delegateCreationExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("method", node.Method, Nothing),
New TreeDumperNode("relaxationLambdaOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationLambdaOpt, Nothing)}),
New TreeDumperNode("relaxationReceiverPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.RelaxationReceiverPlaceholderOpt, Nothing)}),
New TreeDumperNode("methodGroupOpt", Nothing, new TreeDumperNode() {Visit(node.MethodGroupOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayCreation(node As BoundArrayCreation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayCreation", Nothing, New TreeDumperNode() {
New TreeDumperNode("isParamArrayArgument", node.IsParamArrayArgument, Nothing),
New TreeDumperNode("bounds", Nothing, From x In node.Bounds Select Visit(x, Nothing)),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)}),
New TreeDumperNode("arrayLiteralOpt", Nothing, new TreeDumperNode() {Visit(node.ArrayLiteralOpt, Nothing)}),
New TreeDumperNode("arrayLiteralConversion", node.ArrayLiteralConversion, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayLiteral(node As BoundArrayLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayLiteral", Nothing, New TreeDumperNode() {
New TreeDumperNode("hasDominantType", node.HasDominantType, Nothing),
New TreeDumperNode("numberOfCandidates", node.NumberOfCandidates, Nothing),
New TreeDumperNode("inferredType", node.InferredType, Nothing),
New TreeDumperNode("bounds", Nothing, From x In node.Bounds Select Visit(x, Nothing)),
New TreeDumperNode("initializer", Nothing, new TreeDumperNode() {Visit(node.Initializer, Nothing)}),
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitArrayInitialization(node As BoundArrayInitialization, arg As Object) As TreeDumperNode
Return New TreeDumperNode("arrayInitialization", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializers", Nothing, From x In node.Initializers Select Visit(x, Nothing)),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitFieldAccess(node As BoundFieldAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("fieldAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("fieldSymbol", node.FieldSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("suppressVirtualCalls", node.SuppressVirtualCalls, Nothing),
New TreeDumperNode("constantsInProgressOpt", node.ConstantsInProgressOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("propertyAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("propertySymbol", node.PropertySymbol, Nothing),
New TreeDumperNode("propertyGroupOpt", Nothing, new TreeDumperNode() {Visit(node.PropertyGroupOpt, Nothing)}),
New TreeDumperNode("accessKind", node.AccessKind, Nothing),
New TreeDumperNode("isWriteable", node.IsWriteable, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("arguments", Nothing, From x In node.Arguments Select Visit(x, Nothing)),
New TreeDumperNode("defaultArguments", node.DefaultArguments, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitEventAccess(node As BoundEventAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("eventAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOpt", Nothing, new TreeDumperNode() {Visit(node.ReceiverOpt, Nothing)}),
New TreeDumperNode("eventSymbol", node.EventSymbol, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitBlock(node As BoundBlock, arg As Object) As TreeDumperNode
Return New TreeDumperNode("block", Nothing, New TreeDumperNode() {
New TreeDumperNode("statementListSyntax", node.StatementListSyntax, Nothing),
New TreeDumperNode("locals", node.Locals, Nothing),
New TreeDumperNode("statements", Nothing, From x In node.Statements Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitStateMachineScope(node As BoundStateMachineScope, arg As Object) As TreeDumperNode
Return New TreeDumperNode("stateMachineScope", Nothing, New TreeDumperNode() {
New TreeDumperNode("fields", node.Fields, Nothing),
New TreeDumperNode("statement", Nothing, new TreeDumperNode() {Visit(node.Statement, Nothing)})
})
End Function
Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration, arg As Object) As TreeDumperNode
Return New TreeDumperNode("localDeclaration", Nothing, New TreeDumperNode() {
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("declarationInitializerOpt", Nothing, new TreeDumperNode() {Visit(node.DeclarationInitializerOpt, Nothing)}),
New TreeDumperNode("identifierInitializerOpt", Nothing, new TreeDumperNode() {Visit(node.IdentifierInitializerOpt, Nothing)}),
New TreeDumperNode("initializedByAsNew", node.InitializedByAsNew, Nothing)
})
End Function
Public Overrides Function VisitAsNewLocalDeclarations(node As BoundAsNewLocalDeclarations, arg As Object) As TreeDumperNode
Return New TreeDumperNode("asNewLocalDeclarations", Nothing, New TreeDumperNode() {
New TreeDumperNode("localDeclarations", Nothing, From x In node.LocalDeclarations Select Visit(x, Nothing)),
New TreeDumperNode("initializer", Nothing, new TreeDumperNode() {Visit(node.Initializer, Nothing)}),
New TreeDumperNode("binder", node.Binder, Nothing)
})
End Function
Public Overrides Function VisitDimStatement(node As BoundDimStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("dimStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("localDeclarations", Nothing, From x In node.LocalDeclarations Select Visit(x, Nothing)),
New TreeDumperNode("initializerOpt", Nothing, new TreeDumperNode() {Visit(node.InitializerOpt, Nothing)})
})
End Function
Public Overrides Function VisitInitializer(node As BoundInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("initializer", Nothing, Array.Empty(Of TreeDumperNode)())
End Function
Public Overrides Function VisitFieldInitializer(node As BoundFieldInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("fieldInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializedFields", node.InitializedFields, Nothing),
New TreeDumperNode("memberAccessExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.MemberAccessExpressionOpt, Nothing)}),
New TreeDumperNode("initialValue", Nothing, new TreeDumperNode() {Visit(node.InitialValue, Nothing)}),
New TreeDumperNode("binderOpt", node.BinderOpt, Nothing)
})
End Function
Public Overrides Function VisitPropertyInitializer(node As BoundPropertyInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("propertyInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("initializedProperties", node.InitializedProperties, Nothing),
New TreeDumperNode("memberAccessExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.MemberAccessExpressionOpt, Nothing)}),
New TreeDumperNode("initialValue", Nothing, new TreeDumperNode() {Visit(node.InitialValue, Nothing)}),
New TreeDumperNode("binderOpt", node.BinderOpt, Nothing)
})
End Function
Public Overrides Function VisitParameterEqualsValue(node As BoundParameterEqualsValue, arg As Object) As TreeDumperNode
Return New TreeDumperNode("parameterEqualsValue", Nothing, New TreeDumperNode() {
New TreeDumperNode("parameter", node.Parameter, Nothing),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)})
})
End Function
Public Overrides Function VisitGlobalStatementInitializer(node As BoundGlobalStatementInitializer, arg As Object) As TreeDumperNode
Return New TreeDumperNode("globalStatementInitializer", Nothing, New TreeDumperNode() {
New TreeDumperNode("statement", Nothing, new TreeDumperNode() {Visit(node.Statement, Nothing)})
})
End Function
Public Overrides Function VisitSequence(node As BoundSequence, arg As Object) As TreeDumperNode
Return New TreeDumperNode("sequence", Nothing, New TreeDumperNode() {
New TreeDumperNode("locals", node.Locals, Nothing),
New TreeDumperNode("sideEffects", Nothing, From x In node.SideEffects Select Visit(x, Nothing)),
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitExpressionStatement(node As BoundExpressionStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("expressionStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)})
})
End Function
Public Overrides Function VisitIfStatement(node As BoundIfStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("ifStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("consequence", Nothing, new TreeDumperNode() {Visit(node.Consequence, Nothing)}),
New TreeDumperNode("alternativeOpt", Nothing, new TreeDumperNode() {Visit(node.AlternativeOpt, Nothing)})
})
End Function
Public Overrides Function VisitSelectStatement(node As BoundSelectStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("selectStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("expressionStatement", Nothing, new TreeDumperNode() {Visit(node.ExpressionStatement, Nothing)}),
New TreeDumperNode("exprPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.ExprPlaceholderOpt, Nothing)}),
New TreeDumperNode("caseBlocks", Nothing, From x In node.CaseBlocks Select Visit(x, Nothing)),
New TreeDumperNode("recommendSwitchTable", node.RecommendSwitchTable, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitCaseBlock(node As BoundCaseBlock, arg As Object) As TreeDumperNode
Return New TreeDumperNode("caseBlock", Nothing, New TreeDumperNode() {
New TreeDumperNode("caseStatement", Nothing, new TreeDumperNode() {Visit(node.CaseStatement, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)})
})
End Function
Public Overrides Function VisitCaseStatement(node As BoundCaseStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("caseStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("caseClauses", Nothing, From x In node.CaseClauses Select Visit(x, Nothing)),
New TreeDumperNode("conditionOpt", Nothing, new TreeDumperNode() {Visit(node.ConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitSimpleCaseClause(node As BoundSimpleCaseClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("simpleCaseClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("conditionOpt", Nothing, new TreeDumperNode() {Visit(node.ConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitRangeCaseClause(node As BoundRangeCaseClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rangeCaseClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("lowerBoundOpt", Nothing, new TreeDumperNode() {Visit(node.LowerBoundOpt, Nothing)}),
New TreeDumperNode("upperBoundOpt", Nothing, new TreeDumperNode() {Visit(node.UpperBoundOpt, Nothing)}),
New TreeDumperNode("lowerBoundConditionOpt", Nothing, new TreeDumperNode() {Visit(node.LowerBoundConditionOpt, Nothing)}),
New TreeDumperNode("upperBoundConditionOpt", Nothing, new TreeDumperNode() {Visit(node.UpperBoundConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitRelationalCaseClause(node As BoundRelationalCaseClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("relationalCaseClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("operatorKind", node.OperatorKind, Nothing),
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("conditionOpt", Nothing, new TreeDumperNode() {Visit(node.ConditionOpt, Nothing)})
})
End Function
Public Overrides Function VisitDoLoopStatement(node As BoundDoLoopStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("doLoopStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("topConditionOpt", Nothing, new TreeDumperNode() {Visit(node.TopConditionOpt, Nothing)}),
New TreeDumperNode("bottomConditionOpt", Nothing, new TreeDumperNode() {Visit(node.BottomConditionOpt, Nothing)}),
New TreeDumperNode("topConditionIsUntil", node.TopConditionIsUntil, Nothing),
New TreeDumperNode("bottomConditionIsUntil", node.BottomConditionIsUntil, Nothing),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitWhileStatement(node As BoundWhileStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("whileStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitForToUserDefinedOperators(node As BoundForToUserDefinedOperators, arg As Object) As TreeDumperNode
Return New TreeDumperNode("forToUserDefinedOperators", Nothing, New TreeDumperNode() {
New TreeDumperNode("leftOperandPlaceholder", Nothing, new TreeDumperNode() {Visit(node.LeftOperandPlaceholder, Nothing)}),
New TreeDumperNode("rightOperandPlaceholder", Nothing, new TreeDumperNode() {Visit(node.RightOperandPlaceholder, Nothing)}),
New TreeDumperNode("addition", Nothing, new TreeDumperNode() {Visit(node.Addition, Nothing)}),
New TreeDumperNode("subtraction", Nothing, new TreeDumperNode() {Visit(node.Subtraction, Nothing)}),
New TreeDumperNode("lessThanOrEqual", Nothing, new TreeDumperNode() {Visit(node.LessThanOrEqual, Nothing)}),
New TreeDumperNode("greaterThanOrEqual", Nothing, new TreeDumperNode() {Visit(node.GreaterThanOrEqual, Nothing)})
})
End Function
Public Overrides Function VisitForToStatement(node As BoundForToStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("forToStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("initialValue", Nothing, new TreeDumperNode() {Visit(node.InitialValue, Nothing)}),
New TreeDumperNode("limitValue", Nothing, new TreeDumperNode() {Visit(node.LimitValue, Nothing)}),
New TreeDumperNode("stepValue", Nothing, new TreeDumperNode() {Visit(node.StepValue, Nothing)}),
New TreeDumperNode("checked", node.Checked, Nothing),
New TreeDumperNode("operatorsOpt", Nothing, new TreeDumperNode() {Visit(node.OperatorsOpt, Nothing)}),
New TreeDumperNode("declaredOrInferredLocalOpt", node.DeclaredOrInferredLocalOpt, Nothing),
New TreeDumperNode("controlVariable", Nothing, new TreeDumperNode() {Visit(node.ControlVariable, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("nextVariablesOpt", Nothing, From x In node.NextVariablesOpt Select Visit(x, Nothing)),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitForEachStatement(node As BoundForEachStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("forEachStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("collection", Nothing, new TreeDumperNode() {Visit(node.Collection, Nothing)}),
New TreeDumperNode("enumeratorInfo", node.EnumeratorInfo, Nothing),
New TreeDumperNode("declaredOrInferredLocalOpt", node.DeclaredOrInferredLocalOpt, Nothing),
New TreeDumperNode("controlVariable", Nothing, new TreeDumperNode() {Visit(node.ControlVariable, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("nextVariablesOpt", Nothing, From x In node.NextVariablesOpt Select Visit(x, Nothing)),
New TreeDumperNode("continueLabel", node.ContinueLabel, Nothing),
New TreeDumperNode("exitLabel", node.ExitLabel, Nothing)
})
End Function
Public Overrides Function VisitExitStatement(node As BoundExitStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("exitStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitContinueStatement(node As BoundContinueStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("continueStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("tryStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("tryBlock", Nothing, new TreeDumperNode() {Visit(node.TryBlock, Nothing)}),
New TreeDumperNode("catchBlocks", Nothing, From x In node.CatchBlocks Select Visit(x, Nothing)),
New TreeDumperNode("finallyBlockOpt", Nothing, new TreeDumperNode() {Visit(node.FinallyBlockOpt, Nothing)}),
New TreeDumperNode("exitLabelOpt", node.ExitLabelOpt, Nothing)
})
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock, arg As Object) As TreeDumperNode
Return New TreeDumperNode("catchBlock", Nothing, New TreeDumperNode() {
New TreeDumperNode("localOpt", node.LocalOpt, Nothing),
New TreeDumperNode("exceptionSourceOpt", Nothing, new TreeDumperNode() {Visit(node.ExceptionSourceOpt, Nothing)}),
New TreeDumperNode("errorLineNumberOpt", Nothing, new TreeDumperNode() {Visit(node.ErrorLineNumberOpt, Nothing)}),
New TreeDumperNode("exceptionFilterOpt", Nothing, new TreeDumperNode() {Visit(node.ExceptionFilterOpt, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("isSynthesizedAsyncCatchAll", node.IsSynthesizedAsyncCatchAll, Nothing)
})
End Function
Public Overrides Function VisitLiteral(node As BoundLiteral, arg As Object) As TreeDumperNode
Return New TreeDumperNode("literal", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", node.Value, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMeReference(node As BoundMeReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("meReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("valueTypeMeReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("myBaseReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitMyClassReference(node As BoundMyClassReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("myClassReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPreviousSubmissionReference(node As BoundPreviousSubmissionReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("previousSubmissionReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("sourceType", node.SourceType, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference, arg As Object) As TreeDumperNode
Return New TreeDumperNode("hostObjectMemberReference", Nothing, New TreeDumperNode() {
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLocal(node As BoundLocal, arg As Object) As TreeDumperNode
Return New TreeDumperNode("local", Nothing, New TreeDumperNode() {
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitPseudoVariable(node As BoundPseudoVariable, arg As Object) As TreeDumperNode
Return New TreeDumperNode("pseudoVariable", Nothing, New TreeDumperNode() {
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("emitExpressions", node.EmitExpressions, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitParameter(node As BoundParameter, arg As Object) As TreeDumperNode
Return New TreeDumperNode("parameter", Nothing, New TreeDumperNode() {
New TreeDumperNode("parameterSymbol", node.ParameterSymbol, Nothing),
New TreeDumperNode("isLValue", node.IsLValue, Nothing),
New TreeDumperNode("suppressVirtualCalls", node.SuppressVirtualCalls, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitByRefArgumentPlaceholder(node As BoundByRefArgumentPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("byRefArgumentPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("isOut", node.IsOut, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack, arg As Object) As TreeDumperNode
Return New TreeDumperNode("byRefArgumentWithCopyBack", Nothing, New TreeDumperNode() {
New TreeDumperNode("originalArgument", Nothing, new TreeDumperNode() {Visit(node.OriginalArgument, Nothing)}),
New TreeDumperNode("inConversion", Nothing, new TreeDumperNode() {Visit(node.InConversion, Nothing)}),
New TreeDumperNode("inPlaceholder", Nothing, new TreeDumperNode() {Visit(node.InPlaceholder, Nothing)}),
New TreeDumperNode("outConversion", Nothing, new TreeDumperNode() {Visit(node.OutConversion, Nothing)}),
New TreeDumperNode("outPlaceholder", Nothing, new TreeDumperNode() {Visit(node.OutPlaceholder, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLateBoundArgumentSupportingAssignmentWithCapture(node As BoundLateBoundArgumentSupportingAssignmentWithCapture, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lateBoundArgumentSupportingAssignmentWithCapture", Nothing, New TreeDumperNode() {
New TreeDumperNode("originalArgument", Nothing, new TreeDumperNode() {Visit(node.OriginalArgument, Nothing)}),
New TreeDumperNode("localSymbol", node.LocalSymbol, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLabelStatement(node As BoundLabelStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("labelStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitLabel(node As BoundLabel, arg As Object) As TreeDumperNode
Return New TreeDumperNode("label", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGotoStatement(node As BoundGotoStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("gotoStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("label", node.Label, Nothing),
New TreeDumperNode("labelExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.LabelExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitStatementList(node As BoundStatementList, arg As Object) As TreeDumperNode
Return New TreeDumperNode("statementList", Nothing, New TreeDumperNode() {
New TreeDumperNode("statements", Nothing, From x In node.Statements Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitConditionalGoto(node As BoundConditionalGoto, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conditionalGoto", Nothing, New TreeDumperNode() {
New TreeDumperNode("condition", Nothing, new TreeDumperNode() {Visit(node.Condition, Nothing)}),
New TreeDumperNode("jumpIfTrue", node.JumpIfTrue, Nothing),
New TreeDumperNode("label", node.Label, Nothing)
})
End Function
Public Overrides Function VisitWithStatement(node As BoundWithStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("withStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("originalExpression", Nothing, new TreeDumperNode() {Visit(node.OriginalExpression, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("binder", node.Binder, Nothing)
})
End Function
Public Overrides Function VisitUnboundLambda(node As UnboundLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unboundLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("flags", node.Flags, Nothing),
New TreeDumperNode("parameters", node.Parameters, Nothing),
New TreeDumperNode("returnType", node.ReturnType, Nothing),
New TreeDumperNode("bindingCache", node.BindingCache, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLambda(node As BoundLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("lambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("lambdaSymbol", node.LambdaSymbol, Nothing),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("diagnostics", node.Diagnostics, Nothing),
New TreeDumperNode("lambdaBinderOpt", node.LambdaBinderOpt, Nothing),
New TreeDumperNode("delegateRelaxation", node.DelegateRelaxation, Nothing),
New TreeDumperNode("methodConversionKind", node.MethodConversionKind, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryExpression(node As BoundQueryExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("lastOperator", Nothing, new TreeDumperNode() {Visit(node.LastOperator, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQuerySource(node As BoundQuerySource, arg As Object) As TreeDumperNode
Return New TreeDumperNode("querySource", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitToQueryableCollectionConversion(node As BoundToQueryableCollectionConversion, arg As Object) As TreeDumperNode
Return New TreeDumperNode("toQueryableCollectionConversion", Nothing, New TreeDumperNode() {
New TreeDumperNode("conversionCall", Nothing, new TreeDumperNode() {Visit(node.ConversionCall, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryableSource(node As BoundQueryableSource, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryableSource", Nothing, New TreeDumperNode() {
New TreeDumperNode("source", Nothing, new TreeDumperNode() {Visit(node.Source, Nothing)}),
New TreeDumperNode("rangeVariableOpt", node.RangeVariableOpt, Nothing),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("compoundVariableType", node.CompoundVariableType, Nothing),
New TreeDumperNode("binders", node.Binders, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryClause(node As BoundQueryClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("compoundVariableType", node.CompoundVariableType, Nothing),
New TreeDumperNode("binders", node.Binders, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitOrdering(node As BoundOrdering, arg As Object) As TreeDumperNode
Return New TreeDumperNode("ordering", Nothing, New TreeDumperNode() {
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitQueryLambda(node As BoundQueryLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("queryLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("lambdaSymbol", node.LambdaSymbol, Nothing),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("exprIsOperandOfConditionalBranch", node.ExprIsOperandOfConditionalBranch, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRangeVariableAssignment(node As BoundRangeVariableAssignment, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rangeVariableAssignment", Nothing, New TreeDumperNode() {
New TreeDumperNode("rangeVariable", node.RangeVariable, Nothing),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGroupTypeInferenceLambda(node As GroupTypeInferenceLambda, arg As Object) As TreeDumperNode
Return New TreeDumperNode("groupTypeInferenceLambda", Nothing, New TreeDumperNode() {
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("parameters", node.Parameters, Nothing),
New TreeDumperNode("compilation", node.Compilation, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAggregateClause(node As BoundAggregateClause, arg As Object) As TreeDumperNode
Return New TreeDumperNode("aggregateClause", Nothing, New TreeDumperNode() {
New TreeDumperNode("capturedGroupOpt", Nothing, new TreeDumperNode() {Visit(node.CapturedGroupOpt, Nothing)}),
New TreeDumperNode("groupPlaceholderOpt", Nothing, new TreeDumperNode() {Visit(node.GroupPlaceholderOpt, Nothing)}),
New TreeDumperNode("underlyingExpression", Nothing, new TreeDumperNode() {Visit(node.UnderlyingExpression, Nothing)}),
New TreeDumperNode("rangeVariables", node.RangeVariables, Nothing),
New TreeDumperNode("compoundVariableType", node.CompoundVariableType, Nothing),
New TreeDumperNode("binders", node.Binders, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitGroupAggregation(node As BoundGroupAggregation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("groupAggregation", Nothing, New TreeDumperNode() {
New TreeDumperNode("group", Nothing, new TreeDumperNode() {Visit(node.Group, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitRangeVariable(node As BoundRangeVariable, arg As Object) As TreeDumperNode
Return New TreeDumperNode("rangeVariable", Nothing, New TreeDumperNode() {
New TreeDumperNode("rangeVariable", node.RangeVariable, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitAddHandlerStatement(node As BoundAddHandlerStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("addHandlerStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("eventAccess", Nothing, new TreeDumperNode() {Visit(node.EventAccess, Nothing)}),
New TreeDumperNode("handler", Nothing, new TreeDumperNode() {Visit(node.Handler, Nothing)})
})
End Function
Public Overrides Function VisitRemoveHandlerStatement(node As BoundRemoveHandlerStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("removeHandlerStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("eventAccess", Nothing, new TreeDumperNode() {Visit(node.EventAccess, Nothing)}),
New TreeDumperNode("handler", Nothing, new TreeDumperNode() {Visit(node.Handler, Nothing)})
})
End Function
Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("raiseEventStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("eventSymbol", node.EventSymbol, Nothing),
New TreeDumperNode("eventInvocation", Nothing, new TreeDumperNode() {Visit(node.EventInvocation, Nothing)})
})
End Function
Public Overrides Function VisitUsingStatement(node As BoundUsingStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("usingStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("resourceList", Nothing, From x In node.ResourceList Select Visit(x, Nothing)),
New TreeDumperNode("resourceExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.ResourceExpressionOpt, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)}),
New TreeDumperNode("usingInfo", node.UsingInfo, Nothing),
New TreeDumperNode("locals", node.Locals, Nothing)
})
End Function
Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("syncLockStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("lockExpression", Nothing, new TreeDumperNode() {Visit(node.LockExpression, Nothing)}),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)})
})
End Function
Public Overrides Function VisitXmlName(node As BoundXmlName, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlName", Nothing, New TreeDumperNode() {
New TreeDumperNode("xmlNamespace", Nothing, new TreeDumperNode() {Visit(node.XmlNamespace, Nothing)}),
New TreeDumperNode("localName", Nothing, new TreeDumperNode() {Visit(node.LocalName, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlNamespace(node As BoundXmlNamespace, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlNamespace", Nothing, New TreeDumperNode() {
New TreeDumperNode("xmlNamespace", Nothing, new TreeDumperNode() {Visit(node.XmlNamespace, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlDocument(node As BoundXmlDocument, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlDocument", Nothing, New TreeDumperNode() {
New TreeDumperNode("declaration", Nothing, new TreeDumperNode() {Visit(node.Declaration, Nothing)}),
New TreeDumperNode("childNodes", Nothing, From x In node.ChildNodes Select Visit(x, Nothing)),
New TreeDumperNode("rewriterInfo", node.RewriterInfo, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlDeclaration(node As BoundXmlDeclaration, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlDeclaration", Nothing, New TreeDumperNode() {
New TreeDumperNode("version", Nothing, new TreeDumperNode() {Visit(node.Version, Nothing)}),
New TreeDumperNode("encoding", Nothing, new TreeDumperNode() {Visit(node.Encoding, Nothing)}),
New TreeDumperNode("standalone", Nothing, new TreeDumperNode() {Visit(node.Standalone, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlProcessingInstruction(node As BoundXmlProcessingInstruction, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlProcessingInstruction", Nothing, New TreeDumperNode() {
New TreeDumperNode("target", Nothing, new TreeDumperNode() {Visit(node.Target, Nothing)}),
New TreeDumperNode("data", Nothing, new TreeDumperNode() {Visit(node.Data, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlComment(node As BoundXmlComment, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlComment", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlAttribute(node As BoundXmlAttribute, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlAttribute", Nothing, New TreeDumperNode() {
New TreeDumperNode("name", Nothing, new TreeDumperNode() {Visit(node.Name, Nothing)}),
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("matchesImport", node.MatchesImport, Nothing),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlElement(node As BoundXmlElement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlElement", Nothing, New TreeDumperNode() {
New TreeDumperNode("argument", Nothing, new TreeDumperNode() {Visit(node.Argument, Nothing)}),
New TreeDumperNode("childNodes", Nothing, From x In node.ChildNodes Select Visit(x, Nothing)),
New TreeDumperNode("rewriterInfo", node.RewriterInfo, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlMemberAccess(node As BoundXmlMemberAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlMemberAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("memberAccess", Nothing, new TreeDumperNode() {Visit(node.MemberAccess, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlEmbeddedExpression(node As BoundXmlEmbeddedExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlEmbeddedExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitXmlCData(node As BoundXmlCData, arg As Object) As TreeDumperNode
Return New TreeDumperNode("xmlCData", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("objectCreation", Nothing, new TreeDumperNode() {Visit(node.ObjectCreation, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitResumeStatement(node As BoundResumeStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("resumeStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("resumeKind", node.ResumeKind, Nothing),
New TreeDumperNode("labelOpt", node.LabelOpt, Nothing),
New TreeDumperNode("labelExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.LabelExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitOnErrorStatement(node As BoundOnErrorStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("onErrorStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("onErrorKind", node.OnErrorKind, Nothing),
New TreeDumperNode("labelOpt", node.LabelOpt, Nothing),
New TreeDumperNode("labelExpressionOpt", Nothing, new TreeDumperNode() {Visit(node.LabelExpressionOpt, Nothing)})
})
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingStatement(node As BoundUnstructuredExceptionHandlingStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionHandlingStatement", Nothing, New TreeDumperNode() {
New TreeDumperNode("containsOnError", node.ContainsOnError, Nothing),
New TreeDumperNode("containsResume", node.ContainsResume, Nothing),
New TreeDumperNode("resumeWithoutLabelOpt", node.ResumeWithoutLabelOpt, Nothing),
New TreeDumperNode("trackLineNumber", node.TrackLineNumber, Nothing),
New TreeDumperNode("body", Nothing, new TreeDumperNode() {Visit(node.Body, Nothing)})
})
End Function
Public Overrides Function VisitUnstructuredExceptionHandlingCatchFilter(node As BoundUnstructuredExceptionHandlingCatchFilter, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionHandlingCatchFilter", Nothing, New TreeDumperNode() {
New TreeDumperNode("activeHandlerLocal", Nothing, new TreeDumperNode() {Visit(node.ActiveHandlerLocal, Nothing)}),
New TreeDumperNode("resumeTargetLocal", Nothing, new TreeDumperNode() {Visit(node.ResumeTargetLocal, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitUnstructuredExceptionOnErrorSwitch(node As BoundUnstructuredExceptionOnErrorSwitch, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionOnErrorSwitch", Nothing, New TreeDumperNode() {
New TreeDumperNode("value", Nothing, new TreeDumperNode() {Visit(node.Value, Nothing)}),
New TreeDumperNode("jumps", Nothing, From x In node.Jumps Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitUnstructuredExceptionResumeSwitch(node As BoundUnstructuredExceptionResumeSwitch, arg As Object) As TreeDumperNode
Return New TreeDumperNode("unstructuredExceptionResumeSwitch", Nothing, New TreeDumperNode() {
New TreeDumperNode("resumeTargetTemporary", Nothing, new TreeDumperNode() {Visit(node.ResumeTargetTemporary, Nothing)}),
New TreeDumperNode("resumeLabel", Nothing, new TreeDumperNode() {Visit(node.ResumeLabel, Nothing)}),
New TreeDumperNode("resumeNextLabel", Nothing, new TreeDumperNode() {Visit(node.ResumeNextLabel, Nothing)}),
New TreeDumperNode("jumps", Nothing, From x In node.Jumps Select Visit(x, Nothing))
})
End Function
Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("awaitOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("operand", Nothing, new TreeDumperNode() {Visit(node.Operand, Nothing)}),
New TreeDumperNode("awaitableInstancePlaceholder", Nothing, new TreeDumperNode() {Visit(node.AwaitableInstancePlaceholder, Nothing)}),
New TreeDumperNode("getAwaiter", Nothing, new TreeDumperNode() {Visit(node.GetAwaiter, Nothing)}),
New TreeDumperNode("awaiterInstancePlaceholder", Nothing, new TreeDumperNode() {Visit(node.AwaiterInstancePlaceholder, Nothing)}),
New TreeDumperNode("isCompleted", Nothing, new TreeDumperNode() {Visit(node.IsCompleted, Nothing)}),
New TreeDumperNode("getResult", Nothing, new TreeDumperNode() {Visit(node.GetResult, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitSpillSequence(node As BoundSpillSequence, arg As Object) As TreeDumperNode
Return New TreeDumperNode("spillSequence", Nothing, New TreeDumperNode() {
New TreeDumperNode("locals", node.Locals, Nothing),
New TreeDumperNode("spillFields", node.SpillFields, Nothing),
New TreeDumperNode("statements", Nothing, From x In node.Statements Select Visit(x, Nothing)),
New TreeDumperNode("valueOpt", Nothing, new TreeDumperNode() {Visit(node.ValueOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitStopStatement(node As BoundStopStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("stopStatement", Nothing, Array.Empty(Of TreeDumperNode)())
End Function
Public Overrides Function VisitEndStatement(node As BoundEndStatement, arg As Object) As TreeDumperNode
Return New TreeDumperNode("endStatement", Nothing, Array.Empty(Of TreeDumperNode)())
End Function
Public Overrides Function VisitMidResult(node As BoundMidResult, arg As Object) As TreeDumperNode
Return New TreeDumperNode("midResult", Nothing, New TreeDumperNode() {
New TreeDumperNode("original", Nothing, new TreeDumperNode() {Visit(node.Original, Nothing)}),
New TreeDumperNode("start", Nothing, new TreeDumperNode() {Visit(node.Start, Nothing)}),
New TreeDumperNode("lengthOpt", Nothing, new TreeDumperNode() {Visit(node.LengthOpt, Nothing)}),
New TreeDumperNode("source", Nothing, new TreeDumperNode() {Visit(node.Source, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conditionalAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiver", Nothing, new TreeDumperNode() {Visit(node.Receiver, Nothing)}),
New TreeDumperNode("placeholder", Nothing, new TreeDumperNode() {Visit(node.Placeholder, Nothing)}),
New TreeDumperNode("accessExpression", Nothing, new TreeDumperNode() {Visit(node.AccessExpression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitConditionalAccessReceiverPlaceholder(node As BoundConditionalAccessReceiverPlaceholder, arg As Object) As TreeDumperNode
Return New TreeDumperNode("conditionalAccessReceiverPlaceholder", Nothing, New TreeDumperNode() {
New TreeDumperNode("placeholderId", node.PlaceholderId, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitLoweredConditionalAccess(node As BoundLoweredConditionalAccess, arg As Object) As TreeDumperNode
Return New TreeDumperNode("loweredConditionalAccess", Nothing, New TreeDumperNode() {
New TreeDumperNode("receiverOrCondition", Nothing, new TreeDumperNode() {Visit(node.ReceiverOrCondition, Nothing)}),
New TreeDumperNode("captureReceiver", node.CaptureReceiver, Nothing),
New TreeDumperNode("placeholderId", node.PlaceholderId, Nothing),
New TreeDumperNode("whenNotNull", Nothing, new TreeDumperNode() {Visit(node.WhenNotNull, Nothing)}),
New TreeDumperNode("whenNullOpt", Nothing, new TreeDumperNode() {Visit(node.WhenNullOpt, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitComplexConditionalAccessReceiver(node As BoundComplexConditionalAccessReceiver, arg As Object) As TreeDumperNode
Return New TreeDumperNode("complexConditionalAccessReceiver", Nothing, New TreeDumperNode() {
New TreeDumperNode("valueTypeReceiver", Nothing, new TreeDumperNode() {Visit(node.ValueTypeReceiver, Nothing)}),
New TreeDumperNode("referenceTypeReceiver", Nothing, new TreeDumperNode() {Visit(node.ReferenceTypeReceiver, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitNameOfOperator(node As BoundNameOfOperator, arg As Object) As TreeDumperNode
Return New TreeDumperNode("nameOfOperator", Nothing, New TreeDumperNode() {
New TreeDumperNode("argument", Nothing, new TreeDumperNode() {Visit(node.Argument, Nothing)}),
New TreeDumperNode("constantValueOpt", node.ConstantValueOpt, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitTypeAsValueExpression(node As BoundTypeAsValueExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("typeAsValueExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression, arg As Object) As TreeDumperNode
Return New TreeDumperNode("interpolatedStringExpression", Nothing, New TreeDumperNode() {
New TreeDumperNode("contents", Nothing, From x In node.Contents Select Visit(x, Nothing)),
New TreeDumperNode("binder", node.Binder, Nothing),
New TreeDumperNode("type", node.Type, Nothing)
})
End Function
Public Overrides Function VisitInterpolation(node As BoundInterpolation, arg As Object) As TreeDumperNode
Return New TreeDumperNode("interpolation", Nothing, New TreeDumperNode() {
New TreeDumperNode("expression", Nothing, new TreeDumperNode() {Visit(node.Expression, Nothing)}),
New TreeDumperNode("alignmentOpt", Nothing, new TreeDumperNode() {Visit(node.AlignmentOpt, Nothing)}),
New TreeDumperNode("formatStringOpt", Nothing, new TreeDumperNode() {Visit(node.FormatStringOpt, Nothing)})
})
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/VisualStudio/Core/Def/ExternalAccess/ProjectSystem/Api/ProjectSystemReferenceUpdate.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
internal sealed class ProjectSystemReferenceUpdate
{
/// <summary>
/// Indicates action to perform on the reference.
/// </summary>
public ProjectSystemUpdateAction Action { get; }
/// <summary>
/// Gets the reference to be updated.
/// </summary>
public ProjectSystemReferenceInfo ReferenceInfo { get; }
public ProjectSystemReferenceUpdate(ProjectSystemUpdateAction action, ProjectSystemReferenceInfo referenceInfo)
{
Action = action;
ReferenceInfo = referenceInfo;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
internal sealed class ProjectSystemReferenceUpdate
{
/// <summary>
/// Indicates action to perform on the reference.
/// </summary>
public ProjectSystemUpdateAction Action { get; }
/// <summary>
/// Gets the reference to be updated.
/// </summary>
public ProjectSystemReferenceInfo ReferenceInfo { get; }
public ProjectSystemReferenceUpdate(ProjectSystemUpdateAction action, ProjectSystemReferenceInfo referenceInfo)
{
Action = action;
ReferenceInfo = referenceInfo;
}
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/TargetMenuItemViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Editor.Wpf;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph
{
/// <summary>
/// View model used to show the MenuItem for inheritance target.
/// </summary>
internal class TargetMenuItemViewModel : MenuItemViewModel
{
/// <summary>
/// DefinitionItem used for navigation.
/// </summary>
public DefinitionItem.DetachedDefinitionItem DefinitionItem { get; }
// Internal for testing purpose
internal TargetMenuItemViewModel(
string displayContent,
ImageMoniker imageMoniker,
string automationName,
DefinitionItem.DetachedDefinitionItem definitionItem) : base(displayContent, imageMoniker, automationName)
{
DefinitionItem = definitionItem;
}
public static TargetMenuItemViewModel Create(InheritanceTargetItem target)
{
var displayContent = target.DisplayName;
var imageMoniker = target.Glyph.GetImageMoniker();
return new TargetMenuItemViewModel(
displayContent,
imageMoniker,
displayContent,
target.DefinitionItem);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Editor.Wpf;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph
{
/// <summary>
/// View model used to show the MenuItem for inheritance target.
/// </summary>
internal class TargetMenuItemViewModel : MenuItemViewModel
{
/// <summary>
/// DefinitionItem used for navigation.
/// </summary>
public DefinitionItem.DetachedDefinitionItem DefinitionItem { get; }
// Internal for testing purpose
internal TargetMenuItemViewModel(
string displayContent,
ImageMoniker imageMoniker,
string automationName,
DefinitionItem.DetachedDefinitionItem definitionItem) : base(displayContent, imageMoniker, automationName)
{
DefinitionItem = definitionItem;
}
public static TargetMenuItemViewModel Create(InheritanceTargetItem target)
{
var displayContent = target.DisplayName;
var imageMoniker = target.Glyph.GetImageMoniker();
return new TargetMenuItemViewModel(
displayContent,
imageMoniker,
displayContent,
target.DefinitionItem);
}
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.RemoveAnalyzerConfigDocumentUndoUnit.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class VisualStudioWorkspaceImpl
{
private class RemoveAnalyzerConfigDocumentUndoUnit : AbstractRemoveDocumentUndoUnit
{
public RemoveAnalyzerConfigDocumentUndoUnit(
VisualStudioWorkspaceImpl workspace,
DocumentId documentId)
: base(workspace, documentId)
{
}
protected override IReadOnlyList<DocumentId> GetDocumentIds(Project fromProject)
=> fromProject.State.AnalyzerConfigDocumentStates.Ids;
protected override TextDocument? GetDocument(Solution currentSolution)
=> currentSolution.GetAnalyzerConfigDocument(this.DocumentId);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class VisualStudioWorkspaceImpl
{
private class RemoveAnalyzerConfigDocumentUndoUnit : AbstractRemoveDocumentUndoUnit
{
public RemoveAnalyzerConfigDocumentUndoUnit(
VisualStudioWorkspaceImpl workspace,
DocumentId documentId)
: base(workspace, documentId)
{
}
protected override IReadOnlyList<DocumentId> GetDocumentIds(Project fromProject)
=> fromProject.State.AnalyzerConfigDocumentStates.Ids;
protected override TextDocument? GetDocument(Solution currentSolution)
=> currentSolution.GetAnalyzerConfigDocument(this.DocumentId);
}
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/EditorFeatures/VisualBasicTest/EditAndContinue/Helpers/EditingTestBase.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.Differencing
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests
Public MustInherit Class EditingTestBase
Inherits BasicTestBase
Public Shared ReadOnly ReloadableAttributeSrc As String = "
Imports System.Runtime.CompilerServices
Namespace System.Runtime.CompilerServices
Class CreateNewOnMetadataUpdateAttribute
Inherits Attribute
End Class
End Namespace
"
Friend Shared Function CreateAnalyzer() As VisualBasicEditAndContinueAnalyzer
Return New VisualBasicEditAndContinueAnalyzer()
End Function
Public Enum MethodKind
Regular
Async
Iterator
End Enum
Public Shared Function GetResource(keyword As String) As String
Select Case keyword
Case "Class"
Return FeaturesResources.class_
Case "Structure"
Return VBFeaturesResources.structure_
Case "Module"
Return VBFeaturesResources.module_
Case "Interface"
Return FeaturesResources.interface_
Case Else
Throw ExceptionUtilities.UnexpectedValue(keyword)
End Select
End Function
Friend Shared NoSemanticEdits As SemanticEditDescription() = Array.Empty(Of SemanticEditDescription)
Friend Overloads Shared Function Diagnostic(rudeEditKind As RudeEditKind, squiggle As String, ParamArray arguments As String()) As RudeEditDiagnosticDescription
Return New RudeEditDiagnosticDescription(rudeEditKind, squiggle, arguments, firstLine:=Nothing)
End Function
Friend Shared Function SemanticEdit(kind As SemanticEditKind,
symbolProvider As Func(Of Compilation, ISymbol),
syntaxMap As IEnumerable(Of KeyValuePair(Of TextSpan, TextSpan)),
Optional partialType As String = Nothing) As SemanticEditDescription
Return New SemanticEditDescription(
kind,
symbolProvider,
If(partialType Is Nothing, Nothing, Function(c As Compilation) CType(c.GetMember(partialType), ITypeSymbol)),
syntaxMap,
hasSyntaxMap:=syntaxMap IsNot Nothing)
End Function
Friend Shared Function SemanticEdit(kind As SemanticEditKind,
symbolProvider As Func(Of Compilation, ISymbol),
Optional partialType As String = Nothing,
Optional preserveLocalVariables As Boolean = False) As SemanticEditDescription
Return New SemanticEditDescription(
kind,
symbolProvider,
If(partialType Is Nothing, Nothing, Function(c As Compilation) CType(c.GetMember(partialType), ITypeSymbol)),
syntaxMap:=Nothing,
hasSyntaxMap:=preserveLocalVariables)
End Function
Friend Shared Function DeletedSymbolDisplay(kind As String, displayName As String) As String
Return String.Format(FeaturesResources.member_kind_and_name, kind, displayName)
End Function
Friend Shared Function DocumentResults(
Optional activeStatements As ActiveStatementsDescription = Nothing,
Optional semanticEdits As SemanticEditDescription() = Nothing,
Optional diagnostics As RudeEditDiagnosticDescription() = Nothing) As DocumentAnalysisResultsDescription
Return New DocumentAnalysisResultsDescription(activeStatements, semanticEdits, lineEdits:=Nothing, diagnostics)
End Function
Private Shared Function ParseSource(markedSource As String, Optional documentIndex As Integer = 0) As SyntaxTree
Return SyntaxFactory.ParseSyntaxTree(
ActiveStatementsDescription.ClearTags(markedSource),
VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest),
path:=documentIndex.ToString())
End Function
Friend Shared Function GetTopEdits(src1 As String, src2 As String, Optional documentIndex As Integer = 0) As EditScript(Of SyntaxNode)
Dim tree1 = ParseSource(src1, documentIndex)
Dim tree2 = ParseSource(src2, documentIndex)
tree1.GetDiagnostics().Verify()
tree2.GetDiagnostics().Verify()
Dim match = SyntaxComparer.TopLevel.ComputeMatch(tree1.GetRoot(), tree2.GetRoot())
Return match.GetTreeEdits()
End Function
Public Shared Function GetTopEdits(methodEdits As EditScript(Of SyntaxNode)) As EditScript(Of SyntaxNode)
Dim oldMethodSource = methodEdits.Match.OldRoot.ToFullString()
Dim newMethodSource = methodEdits.Match.NewRoot.ToFullString()
Return GetTopEdits(WrapMethodBodyWithClass(oldMethodSource), WrapMethodBodyWithClass(newMethodSource))
End Function
Friend Shared Function GetMethodEdits(src1 As String, src2 As String, Optional methodKind As MethodKind = MethodKind.Regular) As EditScript(Of SyntaxNode)
Dim match = GetMethodMatch(src1, src2, methodKind)
Return match.GetTreeEdits()
End Function
Friend Shared Function GetMethodMatch(src1 As String, src2 As String, Optional methodKind As MethodKind = MethodKind.Regular) As Match(Of SyntaxNode)
Dim m1 = MakeMethodBody(src1, methodKind)
Dim m2 = MakeMethodBody(src2, methodKind)
Dim diagnostics = New ArrayBuilder(Of RudeEditDiagnostic)()
Dim oldHasStateMachineSuspensionPoint = False, newHasStateMachineSuspensionPoint = False
Dim match = CreateAnalyzer().GetTestAccessor().ComputeBodyMatch(m1, m2, Array.Empty(Of AbstractEditAndContinueAnalyzer.ActiveNode)(), diagnostics, oldHasStateMachineSuspensionPoint, newHasStateMachineSuspensionPoint)
Dim needsSyntaxMap = oldHasStateMachineSuspensionPoint AndAlso newHasStateMachineSuspensionPoint
Assert.Equal(methodKind <> MethodKind.Regular, needsSyntaxMap)
If methodKind = MethodKind.Regular Then
Assert.Empty(diagnostics)
End If
Return match
End Function
Public Shared Function GetMethodMatches(src1 As String,
src2 As String,
Optional stateMachine As MethodKind = MethodKind.Regular) As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))
Dim methodMatch = GetMethodMatch(src1, src2, stateMachine)
Return EditAndContinueTestHelpers.GetMethodMatches(CreateAnalyzer(), methodMatch)
End Function
Public Shared Function ToMatchingPairs(match As Match(Of SyntaxNode)) As MatchingPairs
Return EditAndContinueTestHelpers.ToMatchingPairs(match)
End Function
Public Shared Function ToMatchingPairs(matches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As MatchingPairs
Return EditAndContinueTestHelpers.ToMatchingPairs(matches)
End Function
Friend Shared Function MakeMethodBody(bodySource As String, Optional stateMachine As MethodKind = MethodKind.Regular) As SyntaxNode
Dim source = WrapMethodBodyWithClass(bodySource, stateMachine)
Dim tree = ParseSource(source)
Dim root = tree.GetRoot()
tree.GetDiagnostics().Verify()
Dim declaration = DirectCast(DirectCast(root, CompilationUnitSyntax).Members(0), ClassBlockSyntax).Members(0)
Return SyntaxFactory.SyntaxTree(declaration).GetRoot()
End Function
Private Shared Function WrapMethodBodyWithClass(bodySource As String, Optional kind As MethodKind = MethodKind.Regular) As String
Select Case kind
Case MethodKind.Iterator
Return "Class C" & vbLf & "Iterator Function F() As IEnumerable(Of Integer)" & vbLf & bodySource & " : End Function : End Class"
Case MethodKind.Async
Return "Class C" & vbLf & "Async Function F() As Task(Of Integer)" & vbLf & bodySource & " : End Function : End Class"
Case Else
Return "Class C" & vbLf & "Sub F()" & vbLf & bodySource & " : End Sub : End Class"
End Select
End Function
Friend Shared Function GetActiveStatements(oldSource As String, newSource As String, Optional flags As ActiveStatementFlags() = Nothing, Optional path As String = "0") As ActiveStatementsDescription
Return New ActiveStatementsDescription(oldSource, newSource, Function(source) SyntaxFactory.ParseSyntaxTree(source, path:=path), flags)
End Function
Friend Shared Function GetSyntaxMap(oldSource As String, newSource As String) As SyntaxMapDescription
Return New SyntaxMapDescription(oldSource, newSource)
End Function
Friend Shared Function GetActiveStatementDebugInfos(
markedSources As String(),
Optional filePaths As String() = Nothing,
Optional methodRowIds As Integer() = Nothing,
Optional modules As Guid() = Nothing,
Optional methodVersions As Integer() = Nothing,
Optional ilOffsets As Integer() = Nothing,
Optional flags As ActiveStatementFlags() = Nothing) As ImmutableArray(Of ManagedActiveStatementDebugInfo)
Return ActiveStatementsDescription.GetActiveStatementDebugInfos(
Function(source, path) SyntaxFactory.ParseSyntaxTree(source, path:=path),
markedSources,
filePaths,
extension:=".vb",
methodRowIds,
modules,
methodVersions,
ilOffsets,
flags)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Differencing
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EditAndContinue
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests
Public MustInherit Class EditingTestBase
Inherits BasicTestBase
Public Shared ReadOnly ReloadableAttributeSrc As String = "
Imports System.Runtime.CompilerServices
Namespace System.Runtime.CompilerServices
Class CreateNewOnMetadataUpdateAttribute
Inherits Attribute
End Class
End Namespace
"
Friend Shared Function CreateAnalyzer() As VisualBasicEditAndContinueAnalyzer
Return New VisualBasicEditAndContinueAnalyzer()
End Function
Public Enum MethodKind
Regular
Async
Iterator
End Enum
Public Shared Function GetResource(keyword As String) As String
Select Case keyword
Case "Class"
Return FeaturesResources.class_
Case "Structure"
Return VBFeaturesResources.structure_
Case "Module"
Return VBFeaturesResources.module_
Case "Interface"
Return FeaturesResources.interface_
Case Else
Throw ExceptionUtilities.UnexpectedValue(keyword)
End Select
End Function
Friend Shared NoSemanticEdits As SemanticEditDescription() = Array.Empty(Of SemanticEditDescription)
Friend Overloads Shared Function Diagnostic(rudeEditKind As RudeEditKind, squiggle As String, ParamArray arguments As String()) As RudeEditDiagnosticDescription
Return New RudeEditDiagnosticDescription(rudeEditKind, squiggle, arguments, firstLine:=Nothing)
End Function
Friend Shared Function SemanticEdit(kind As SemanticEditKind,
symbolProvider As Func(Of Compilation, ISymbol),
syntaxMap As IEnumerable(Of KeyValuePair(Of TextSpan, TextSpan)),
Optional partialType As String = Nothing) As SemanticEditDescription
Return New SemanticEditDescription(
kind,
symbolProvider,
If(partialType Is Nothing, Nothing, Function(c As Compilation) CType(c.GetMember(partialType), ITypeSymbol)),
syntaxMap,
hasSyntaxMap:=syntaxMap IsNot Nothing)
End Function
Friend Shared Function SemanticEdit(kind As SemanticEditKind,
symbolProvider As Func(Of Compilation, ISymbol),
Optional partialType As String = Nothing,
Optional preserveLocalVariables As Boolean = False) As SemanticEditDescription
Return New SemanticEditDescription(
kind,
symbolProvider,
If(partialType Is Nothing, Nothing, Function(c As Compilation) CType(c.GetMember(partialType), ITypeSymbol)),
syntaxMap:=Nothing,
hasSyntaxMap:=preserveLocalVariables)
End Function
Friend Shared Function DeletedSymbolDisplay(kind As String, displayName As String) As String
Return String.Format(FeaturesResources.member_kind_and_name, kind, displayName)
End Function
Friend Shared Function DocumentResults(
Optional activeStatements As ActiveStatementsDescription = Nothing,
Optional semanticEdits As SemanticEditDescription() = Nothing,
Optional diagnostics As RudeEditDiagnosticDescription() = Nothing) As DocumentAnalysisResultsDescription
Return New DocumentAnalysisResultsDescription(activeStatements, semanticEdits, lineEdits:=Nothing, diagnostics)
End Function
Private Shared Function ParseSource(markedSource As String, Optional documentIndex As Integer = 0) As SyntaxTree
Return SyntaxFactory.ParseSyntaxTree(
ActiveStatementsDescription.ClearTags(markedSource),
VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest),
path:=documentIndex.ToString())
End Function
Friend Shared Function GetTopEdits(src1 As String, src2 As String, Optional documentIndex As Integer = 0) As EditScript(Of SyntaxNode)
Dim tree1 = ParseSource(src1, documentIndex)
Dim tree2 = ParseSource(src2, documentIndex)
tree1.GetDiagnostics().Verify()
tree2.GetDiagnostics().Verify()
Dim match = SyntaxComparer.TopLevel.ComputeMatch(tree1.GetRoot(), tree2.GetRoot())
Return match.GetTreeEdits()
End Function
Public Shared Function GetTopEdits(methodEdits As EditScript(Of SyntaxNode)) As EditScript(Of SyntaxNode)
Dim oldMethodSource = methodEdits.Match.OldRoot.ToFullString()
Dim newMethodSource = methodEdits.Match.NewRoot.ToFullString()
Return GetTopEdits(WrapMethodBodyWithClass(oldMethodSource), WrapMethodBodyWithClass(newMethodSource))
End Function
Friend Shared Function GetMethodEdits(src1 As String, src2 As String, Optional methodKind As MethodKind = MethodKind.Regular) As EditScript(Of SyntaxNode)
Dim match = GetMethodMatch(src1, src2, methodKind)
Return match.GetTreeEdits()
End Function
Friend Shared Function GetMethodMatch(src1 As String, src2 As String, Optional methodKind As MethodKind = MethodKind.Regular) As Match(Of SyntaxNode)
Dim m1 = MakeMethodBody(src1, methodKind)
Dim m2 = MakeMethodBody(src2, methodKind)
Dim diagnostics = New ArrayBuilder(Of RudeEditDiagnostic)()
Dim oldHasStateMachineSuspensionPoint = False, newHasStateMachineSuspensionPoint = False
Dim match = CreateAnalyzer().GetTestAccessor().ComputeBodyMatch(m1, m2, Array.Empty(Of AbstractEditAndContinueAnalyzer.ActiveNode)(), diagnostics, oldHasStateMachineSuspensionPoint, newHasStateMachineSuspensionPoint)
Dim needsSyntaxMap = oldHasStateMachineSuspensionPoint AndAlso newHasStateMachineSuspensionPoint
Assert.Equal(methodKind <> MethodKind.Regular, needsSyntaxMap)
If methodKind = MethodKind.Regular Then
Assert.Empty(diagnostics)
End If
Return match
End Function
Public Shared Function GetMethodMatches(src1 As String,
src2 As String,
Optional stateMachine As MethodKind = MethodKind.Regular) As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))
Dim methodMatch = GetMethodMatch(src1, src2, stateMachine)
Return EditAndContinueTestHelpers.GetMethodMatches(CreateAnalyzer(), methodMatch)
End Function
Public Shared Function ToMatchingPairs(match As Match(Of SyntaxNode)) As MatchingPairs
Return EditAndContinueTestHelpers.ToMatchingPairs(match)
End Function
Public Shared Function ToMatchingPairs(matches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As MatchingPairs
Return EditAndContinueTestHelpers.ToMatchingPairs(matches)
End Function
Friend Shared Function MakeMethodBody(bodySource As String, Optional stateMachine As MethodKind = MethodKind.Regular) As SyntaxNode
Dim source = WrapMethodBodyWithClass(bodySource, stateMachine)
Dim tree = ParseSource(source)
Dim root = tree.GetRoot()
tree.GetDiagnostics().Verify()
Dim declaration = DirectCast(DirectCast(root, CompilationUnitSyntax).Members(0), ClassBlockSyntax).Members(0)
Return SyntaxFactory.SyntaxTree(declaration).GetRoot()
End Function
Private Shared Function WrapMethodBodyWithClass(bodySource As String, Optional kind As MethodKind = MethodKind.Regular) As String
Select Case kind
Case MethodKind.Iterator
Return "Class C" & vbLf & "Iterator Function F() As IEnumerable(Of Integer)" & vbLf & bodySource & " : End Function : End Class"
Case MethodKind.Async
Return "Class C" & vbLf & "Async Function F() As Task(Of Integer)" & vbLf & bodySource & " : End Function : End Class"
Case Else
Return "Class C" & vbLf & "Sub F()" & vbLf & bodySource & " : End Sub : End Class"
End Select
End Function
Friend Shared Function GetActiveStatements(oldSource As String, newSource As String, Optional flags As ActiveStatementFlags() = Nothing, Optional path As String = "0") As ActiveStatementsDescription
Return New ActiveStatementsDescription(oldSource, newSource, Function(source) SyntaxFactory.ParseSyntaxTree(source, path:=path), flags)
End Function
Friend Shared Function GetSyntaxMap(oldSource As String, newSource As String) As SyntaxMapDescription
Return New SyntaxMapDescription(oldSource, newSource)
End Function
Friend Shared Function GetActiveStatementDebugInfos(
markedSources As String(),
Optional filePaths As String() = Nothing,
Optional methodRowIds As Integer() = Nothing,
Optional modules As Guid() = Nothing,
Optional methodVersions As Integer() = Nothing,
Optional ilOffsets As Integer() = Nothing,
Optional flags As ActiveStatementFlags() = Nothing) As ImmutableArray(Of ManagedActiveStatementDebugInfo)
Return ActiveStatementsDescription.GetActiveStatementDebugInfos(
Function(source, path) SyntaxFactory.ParseSyntaxTree(source, path:=path),
markedSources,
filePaths,
extension:=".vb",
methodRowIds,
modules,
methodVersions,
ilOffsets,
flags)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Features/Core/Portable/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeMemberStatic
{
internal abstract class AbstractMakeMemberStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile;
protected abstract bool TryGetMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? memberDeclaration);
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
if (context.Diagnostics.Length == 1 &&
TryGetMemberDeclaration(context.Diagnostics[0].Location.FindNode(context.CancellationToken), out _))
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
}
return Task.CompletedTask;
}
protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
for (var i = 0; i < diagnostics.Length; i++)
{
var declaration = diagnostics[i].Location.FindNode(cancellationToken);
if (TryGetMemberDeclaration(declaration, out var memberDeclaration))
{
var generator = SyntaxGenerator.GetGenerator(document);
var newNode = generator.WithModifiers(memberDeclaration, generator.GetModifiers(declaration).WithIsStatic(true));
editor.ReplaceNode(declaration, newNode);
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Make_member_static, createChangedDocument, nameof(AbstractMakeMemberStaticCodeFixProvider))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeMemberStatic
{
internal abstract class AbstractMakeMemberStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile;
protected abstract bool TryGetMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? memberDeclaration);
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
if (context.Diagnostics.Length == 1 &&
TryGetMemberDeclaration(context.Diagnostics[0].Location.FindNode(context.CancellationToken), out _))
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
}
return Task.CompletedTask;
}
protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
for (var i = 0; i < diagnostics.Length; i++)
{
var declaration = diagnostics[i].Location.FindNode(cancellationToken);
if (TryGetMemberDeclaration(declaration, out var memberDeclaration))
{
var generator = SyntaxGenerator.GetGenerator(document);
var newNode = generator.WithModifiers(memberDeclaration, generator.GetModifiers(declaration).WithIsStatic(true));
editor.ReplaceNode(declaration, newNode);
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Make_member_static, createChangedDocument, nameof(AbstractMakeMemberStaticCodeFixProvider))
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Compilers/CSharp/Portable/Syntax/SyntaxKindFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CSharp
{
public static partial class SyntaxFacts
{
public static bool IsKeywordKind(SyntaxKind kind)
{
return IsReservedKeyword(kind) || IsContextualKeyword(kind);
}
public static IEnumerable<SyntaxKind> GetReservedKeywordKinds()
{
for (int i = (int)SyntaxKind.BoolKeyword; i <= (int)SyntaxKind.ImplicitKeyword; i++)
{
yield return (SyntaxKind)i;
}
}
public static IEnumerable<SyntaxKind> GetKeywordKinds()
{
foreach (var reserved in GetReservedKeywordKinds())
{
yield return reserved;
}
foreach (var contextual in GetContextualKeywordKinds())
{
yield return contextual;
}
}
public static bool IsReservedKeyword(SyntaxKind kind)
{
return kind >= SyntaxKind.BoolKeyword && kind <= SyntaxKind.ImplicitKeyword;
}
public static bool IsAttributeTargetSpecifier(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.AssemblyKeyword:
case SyntaxKind.ModuleKeyword:
return true;
default:
return false;
}
}
public static bool IsAccessibilityModifier(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.PublicKeyword:
return true;
default:
return false;
}
}
public static bool IsPreprocessorKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.IfKeyword:
case SyntaxKind.ElseKeyword:
case SyntaxKind.ElifKeyword:
case SyntaxKind.EndIfKeyword:
case SyntaxKind.RegionKeyword:
case SyntaxKind.EndRegionKeyword:
case SyntaxKind.DefineKeyword:
case SyntaxKind.UndefKeyword:
case SyntaxKind.WarningKeyword:
case SyntaxKind.ErrorKeyword:
case SyntaxKind.LineKeyword:
case SyntaxKind.PragmaKeyword:
case SyntaxKind.HiddenKeyword:
case SyntaxKind.ChecksumKeyword:
case SyntaxKind.DisableKeyword:
case SyntaxKind.RestoreKeyword:
case SyntaxKind.ReferenceKeyword:
case SyntaxKind.LoadKeyword:
case SyntaxKind.NullableKeyword:
case SyntaxKind.EnableKeyword:
case SyntaxKind.WarningsKeyword:
case SyntaxKind.AnnotationsKeyword:
return true;
default:
return false;
}
}
/// <summary>
/// Some preprocessor keywords are only keywords when they appear after a
/// hash sign (#). For these keywords, the lexer will produce tokens with
/// Kind = SyntaxKind.IdentifierToken and ContextualKind set to the keyword
/// SyntaxKind.
/// </summary>
/// <remarks>
/// This wrinkle is specifically not publicly exposed.
/// </remarks>
internal static bool IsPreprocessorContextualKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.HiddenKeyword:
case SyntaxKind.ChecksumKeyword:
case SyntaxKind.DisableKeyword:
case SyntaxKind.RestoreKeyword:
case SyntaxKind.EnableKeyword:
case SyntaxKind.WarningsKeyword:
case SyntaxKind.AnnotationsKeyword:
return false;
default:
return IsPreprocessorKeyword(kind);
}
}
public static IEnumerable<SyntaxKind> GetPreprocessorKeywordKinds()
{
yield return SyntaxKind.TrueKeyword;
yield return SyntaxKind.FalseKeyword;
yield return SyntaxKind.DefaultKeyword;
yield return SyntaxKind.HiddenKeyword;
for (int i = (int)SyntaxKind.ElifKeyword; i <= (int)SyntaxKind.RestoreKeyword; i++)
{
yield return (SyntaxKind)i;
}
}
public static bool IsPunctuation(SyntaxKind kind)
{
return kind >= SyntaxKind.TildeToken && kind <= SyntaxKind.QuestionQuestionEqualsToken;
}
public static bool IsLanguagePunctuation(SyntaxKind kind)
{
return IsPunctuation(kind) && !IsPreprocessorKeyword(kind) && !IsDebuggerSpecialPunctuation(kind);
}
public static bool IsPreprocessorPunctuation(SyntaxKind kind)
{
return kind == SyntaxKind.HashToken;
}
private static bool IsDebuggerSpecialPunctuation(SyntaxKind kind)
{
// TODO: What about "<>f_AnonymousMethod"? Or "123#"? What's this used for?
return kind == SyntaxKind.DollarToken;
}
public static IEnumerable<SyntaxKind> GetPunctuationKinds()
{
for (int i = (int)SyntaxKind.TildeToken; i <= (int)SyntaxKind.PercentEqualsToken; i++)
{
yield return (SyntaxKind)i;
}
}
public static bool IsPunctuationOrKeyword(SyntaxKind kind)
{
return kind >= SyntaxKind.TildeToken && kind <= SyntaxKind.EndOfFileToken;
}
internal static bool IsLiteral(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.IdentifierToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.XmlTextLiteralToken:
case SyntaxKind.XmlTextLiteralNewLineToken:
case SyntaxKind.XmlEntityLiteralToken:
//case SyntaxKind.Unknown:
return true;
default:
return false;
}
}
public static bool IsAnyToken(SyntaxKind kind)
{
if (kind >= SyntaxKind.TildeToken && kind < SyntaxKind.EndOfLineTrivia) return true;
switch (kind)
{
case SyntaxKind.InterpolatedStringToken:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.LoadKeyword:
case SyntaxKind.NullableKeyword:
case SyntaxKind.EnableKeyword:
case SyntaxKind.UnderscoreToken:
return true;
default:
return false;
}
}
public static bool IsTrivia(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.EndOfLineTrivia:
case SyntaxKind.WhitespaceTrivia:
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineDocumentationCommentTrivia:
case SyntaxKind.MultiLineDocumentationCommentTrivia:
case SyntaxKind.DisabledTextTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
case SyntaxKind.ConflictMarkerTrivia:
return true;
default:
return IsPreprocessorDirective(kind);
}
}
public static bool IsPreprocessorDirective(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.IfDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.EndIfDirectiveTrivia:
case SyntaxKind.RegionDirectiveTrivia:
case SyntaxKind.EndRegionDirectiveTrivia:
case SyntaxKind.DefineDirectiveTrivia:
case SyntaxKind.UndefDirectiveTrivia:
case SyntaxKind.ErrorDirectiveTrivia:
case SyntaxKind.WarningDirectiveTrivia:
case SyntaxKind.LineDirectiveTrivia:
case SyntaxKind.LineSpanDirectiveTrivia:
case SyntaxKind.PragmaWarningDirectiveTrivia:
case SyntaxKind.PragmaChecksumDirectiveTrivia:
case SyntaxKind.ReferenceDirectiveTrivia:
case SyntaxKind.LoadDirectiveTrivia:
case SyntaxKind.BadDirectiveTrivia:
case SyntaxKind.ShebangDirectiveTrivia:
case SyntaxKind.NullableDirectiveTrivia:
return true;
default:
return false;
}
}
public static bool IsName(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.QualifiedName:
case SyntaxKind.AliasQualifiedName:
return true;
default:
return false;
}
}
public static bool IsPredefinedType(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.BoolKeyword:
case SyntaxKind.ByteKeyword:
case SyntaxKind.SByteKeyword:
case SyntaxKind.IntKeyword:
case SyntaxKind.UIntKeyword:
case SyntaxKind.ShortKeyword:
case SyntaxKind.UShortKeyword:
case SyntaxKind.LongKeyword:
case SyntaxKind.ULongKeyword:
case SyntaxKind.FloatKeyword:
case SyntaxKind.DoubleKeyword:
case SyntaxKind.DecimalKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.CharKeyword:
case SyntaxKind.ObjectKeyword:
case SyntaxKind.VoidKeyword:
return true;
default:
return false;
}
}
public static bool IsTypeSyntax(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ArrayType:
case SyntaxKind.PointerType:
case SyntaxKind.NullableType:
case SyntaxKind.PredefinedType:
case SyntaxKind.TupleType:
case SyntaxKind.FunctionPointerType:
return true;
default:
return IsName(kind);
}
}
/// <summary>
/// Member declarations that can appear in global code (other than type declarations).
/// </summary>
public static bool IsGlobalMemberDeclaration(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.GlobalStatement:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
return true;
}
return false;
}
public static bool IsTypeDeclaration(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return true;
default:
return false;
}
}
public static bool IsNamespaceMemberDeclaration(SyntaxKind kind)
=> IsTypeDeclaration(kind) ||
kind == SyntaxKind.NamespaceDeclaration ||
kind == SyntaxKind.FileScopedNamespaceDeclaration;
public static bool IsAnyUnaryExpression(SyntaxKind token)
{
return IsPrefixUnaryExpression(token) || IsPostfixUnaryExpression(token);
}
public static bool IsPrefixUnaryExpression(SyntaxKind token)
{
return GetPrefixUnaryExpression(token) != SyntaxKind.None;
}
public static bool IsPrefixUnaryExpressionOperatorToken(SyntaxKind token)
{
return GetPrefixUnaryExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetPrefixUnaryExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.PlusToken:
return SyntaxKind.UnaryPlusExpression;
case SyntaxKind.MinusToken:
return SyntaxKind.UnaryMinusExpression;
case SyntaxKind.TildeToken:
return SyntaxKind.BitwiseNotExpression;
case SyntaxKind.ExclamationToken:
return SyntaxKind.LogicalNotExpression;
case SyntaxKind.PlusPlusToken:
return SyntaxKind.PreIncrementExpression;
case SyntaxKind.MinusMinusToken:
return SyntaxKind.PreDecrementExpression;
case SyntaxKind.AmpersandToken:
return SyntaxKind.AddressOfExpression;
case SyntaxKind.AsteriskToken:
return SyntaxKind.PointerIndirectionExpression;
case SyntaxKind.CaretToken:
return SyntaxKind.IndexExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsPostfixUnaryExpression(SyntaxKind token)
{
return GetPostfixUnaryExpression(token) != SyntaxKind.None;
}
public static bool IsPostfixUnaryExpressionToken(SyntaxKind token)
{
return GetPostfixUnaryExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetPostfixUnaryExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.PlusPlusToken:
return SyntaxKind.PostIncrementExpression;
case SyntaxKind.MinusMinusToken:
return SyntaxKind.PostDecrementExpression;
case SyntaxKind.ExclamationToken:
return SyntaxKind.SuppressNullableWarningExpression;
default:
return SyntaxKind.None;
}
}
internal static bool IsIncrementOrDecrementOperator(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
return true;
default:
return false;
}
}
public static bool IsUnaryOperatorDeclarationToken(SyntaxKind token)
{
return IsPrefixUnaryExpressionOperatorToken(token) ||
token == SyntaxKind.TrueKeyword ||
token == SyntaxKind.FalseKeyword;
}
public static bool IsAnyOverloadableOperator(SyntaxKind kind)
{
return IsOverloadableBinaryOperator(kind) || IsOverloadableUnaryOperator(kind);
}
public static bool IsOverloadableBinaryOperator(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.AsteriskToken:
case SyntaxKind.SlashToken:
case SyntaxKind.PercentToken:
case SyntaxKind.CaretToken:
case SyntaxKind.AmpersandToken:
case SyntaxKind.BarToken:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.LessThanEqualsToken:
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.GreaterThanToken:
case SyntaxKind.GreaterThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.ExclamationEqualsToken:
return true;
default:
return false;
}
}
public static bool IsOverloadableUnaryOperator(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.TildeToken:
case SyntaxKind.ExclamationToken:
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
return true;
default:
return false;
}
}
public static bool IsPrimaryFunction(SyntaxKind keyword)
{
return GetPrimaryFunction(keyword) != SyntaxKind.None;
}
public static SyntaxKind GetPrimaryFunction(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.MakeRefKeyword:
return SyntaxKind.MakeRefExpression;
case SyntaxKind.RefTypeKeyword:
return SyntaxKind.RefTypeExpression;
case SyntaxKind.RefValueKeyword:
return SyntaxKind.RefValueExpression;
case SyntaxKind.CheckedKeyword:
return SyntaxKind.CheckedExpression;
case SyntaxKind.UncheckedKeyword:
return SyntaxKind.UncheckedExpression;
case SyntaxKind.DefaultKeyword:
return SyntaxKind.DefaultExpression;
case SyntaxKind.TypeOfKeyword:
return SyntaxKind.TypeOfExpression;
case SyntaxKind.SizeOfKeyword:
return SyntaxKind.SizeOfExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsLiteralExpression(SyntaxKind token)
{
return GetLiteralExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetLiteralExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.StringLiteralToken:
return SyntaxKind.StringLiteralExpression;
case SyntaxKind.CharacterLiteralToken:
return SyntaxKind.CharacterLiteralExpression;
case SyntaxKind.NumericLiteralToken:
return SyntaxKind.NumericLiteralExpression;
case SyntaxKind.NullKeyword:
return SyntaxKind.NullLiteralExpression;
case SyntaxKind.TrueKeyword:
return SyntaxKind.TrueLiteralExpression;
case SyntaxKind.FalseKeyword:
return SyntaxKind.FalseLiteralExpression;
case SyntaxKind.ArgListKeyword:
return SyntaxKind.ArgListExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsInstanceExpression(SyntaxKind token)
{
return GetInstanceExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetInstanceExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.ThisKeyword:
return SyntaxKind.ThisExpression;
case SyntaxKind.BaseKeyword:
return SyntaxKind.BaseExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsBinaryExpression(SyntaxKind token)
{
return GetBinaryExpression(token) != SyntaxKind.None;
}
public static bool IsBinaryExpressionOperatorToken(SyntaxKind token)
{
return GetBinaryExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetBinaryExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.QuestionQuestionToken:
return SyntaxKind.CoalesceExpression;
case SyntaxKind.IsKeyword:
return SyntaxKind.IsExpression;
case SyntaxKind.AsKeyword:
return SyntaxKind.AsExpression;
case SyntaxKind.BarToken:
return SyntaxKind.BitwiseOrExpression;
case SyntaxKind.CaretToken:
return SyntaxKind.ExclusiveOrExpression;
case SyntaxKind.AmpersandToken:
return SyntaxKind.BitwiseAndExpression;
case SyntaxKind.EqualsEqualsToken:
return SyntaxKind.EqualsExpression;
case SyntaxKind.ExclamationEqualsToken:
return SyntaxKind.NotEqualsExpression;
case SyntaxKind.LessThanToken:
return SyntaxKind.LessThanExpression;
case SyntaxKind.LessThanEqualsToken:
return SyntaxKind.LessThanOrEqualExpression;
case SyntaxKind.GreaterThanToken:
return SyntaxKind.GreaterThanExpression;
case SyntaxKind.GreaterThanEqualsToken:
return SyntaxKind.GreaterThanOrEqualExpression;
case SyntaxKind.LessThanLessThanToken:
return SyntaxKind.LeftShiftExpression;
case SyntaxKind.GreaterThanGreaterThanToken:
return SyntaxKind.RightShiftExpression;
case SyntaxKind.PlusToken:
return SyntaxKind.AddExpression;
case SyntaxKind.MinusToken:
return SyntaxKind.SubtractExpression;
case SyntaxKind.AsteriskToken:
return SyntaxKind.MultiplyExpression;
case SyntaxKind.SlashToken:
return SyntaxKind.DivideExpression;
case SyntaxKind.PercentToken:
return SyntaxKind.ModuloExpression;
case SyntaxKind.AmpersandAmpersandToken:
return SyntaxKind.LogicalAndExpression;
case SyntaxKind.BarBarToken:
return SyntaxKind.LogicalOrExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsAssignmentExpression(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.CoalesceAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.SimpleAssignmentExpression:
return true;
default:
return false;
}
}
public static bool IsAssignmentExpressionOperatorToken(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.QuestionQuestionEqualsToken:
case SyntaxKind.BarEqualsToken:
case SyntaxKind.AmpersandEqualsToken:
case SyntaxKind.CaretEqualsToken:
case SyntaxKind.LessThanLessThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
case SyntaxKind.PlusEqualsToken:
case SyntaxKind.MinusEqualsToken:
case SyntaxKind.AsteriskEqualsToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.PercentEqualsToken:
case SyntaxKind.EqualsToken:
return true;
default:
return false;
}
}
public static SyntaxKind GetAssignmentExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.BarEqualsToken:
return SyntaxKind.OrAssignmentExpression;
case SyntaxKind.AmpersandEqualsToken:
return SyntaxKind.AndAssignmentExpression;
case SyntaxKind.CaretEqualsToken:
return SyntaxKind.ExclusiveOrAssignmentExpression;
case SyntaxKind.LessThanLessThanEqualsToken:
return SyntaxKind.LeftShiftAssignmentExpression;
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return SyntaxKind.RightShiftAssignmentExpression;
case SyntaxKind.PlusEqualsToken:
return SyntaxKind.AddAssignmentExpression;
case SyntaxKind.MinusEqualsToken:
return SyntaxKind.SubtractAssignmentExpression;
case SyntaxKind.AsteriskEqualsToken:
return SyntaxKind.MultiplyAssignmentExpression;
case SyntaxKind.SlashEqualsToken:
return SyntaxKind.DivideAssignmentExpression;
case SyntaxKind.PercentEqualsToken:
return SyntaxKind.ModuloAssignmentExpression;
case SyntaxKind.EqualsToken:
return SyntaxKind.SimpleAssignmentExpression;
case SyntaxKind.QuestionQuestionEqualsToken:
return SyntaxKind.CoalesceAssignmentExpression;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetCheckStatement(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.CheckedKeyword:
return SyntaxKind.CheckedStatement;
case SyntaxKind.UncheckedKeyword:
return SyntaxKind.UncheckedStatement;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetAccessorDeclarationKind(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.GetKeyword:
return SyntaxKind.GetAccessorDeclaration;
case SyntaxKind.SetKeyword:
return SyntaxKind.SetAccessorDeclaration;
case SyntaxKind.InitKeyword:
return SyntaxKind.InitAccessorDeclaration;
case SyntaxKind.AddKeyword:
return SyntaxKind.AddAccessorDeclaration;
case SyntaxKind.RemoveKeyword:
return SyntaxKind.RemoveAccessorDeclaration;
default:
return SyntaxKind.None;
}
}
public static bool IsAccessorDeclaration(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
default:
return false;
}
}
public static bool IsAccessorDeclarationKeyword(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.InitKeyword:
case SyntaxKind.AddKeyword:
case SyntaxKind.RemoveKeyword:
return true;
default:
return false;
}
}
public static SyntaxKind GetSwitchLabelKind(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.CaseKeyword:
return SyntaxKind.CaseSwitchLabel;
case SyntaxKind.DefaultKeyword:
return SyntaxKind.DefaultSwitchLabel;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetBaseTypeDeclarationKind(SyntaxKind kind)
{
return kind == SyntaxKind.EnumKeyword ? SyntaxKind.EnumDeclaration : GetTypeDeclarationKind(kind);
}
public static SyntaxKind GetTypeDeclarationKind(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ClassKeyword:
return SyntaxKind.ClassDeclaration;
case SyntaxKind.StructKeyword:
return SyntaxKind.StructDeclaration;
case SyntaxKind.InterfaceKeyword:
return SyntaxKind.InterfaceDeclaration;
case SyntaxKind.RecordKeyword:
return SyntaxKind.RecordDeclaration;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetKeywordKind(string text)
{
switch (text)
{
case "bool":
return SyntaxKind.BoolKeyword;
case "byte":
return SyntaxKind.ByteKeyword;
case "sbyte":
return SyntaxKind.SByteKeyword;
case "short":
return SyntaxKind.ShortKeyword;
case "ushort":
return SyntaxKind.UShortKeyword;
case "int":
return SyntaxKind.IntKeyword;
case "uint":
return SyntaxKind.UIntKeyword;
case "long":
return SyntaxKind.LongKeyword;
case "ulong":
return SyntaxKind.ULongKeyword;
case "double":
return SyntaxKind.DoubleKeyword;
case "float":
return SyntaxKind.FloatKeyword;
case "decimal":
return SyntaxKind.DecimalKeyword;
case "string":
return SyntaxKind.StringKeyword;
case "char":
return SyntaxKind.CharKeyword;
case "void":
return SyntaxKind.VoidKeyword;
case "object":
return SyntaxKind.ObjectKeyword;
case "typeof":
return SyntaxKind.TypeOfKeyword;
case "sizeof":
return SyntaxKind.SizeOfKeyword;
case "null":
return SyntaxKind.NullKeyword;
case "true":
return SyntaxKind.TrueKeyword;
case "false":
return SyntaxKind.FalseKeyword;
case "if":
return SyntaxKind.IfKeyword;
case "else":
return SyntaxKind.ElseKeyword;
case "while":
return SyntaxKind.WhileKeyword;
case "for":
return SyntaxKind.ForKeyword;
case "foreach":
return SyntaxKind.ForEachKeyword;
case "do":
return SyntaxKind.DoKeyword;
case "switch":
return SyntaxKind.SwitchKeyword;
case "case":
return SyntaxKind.CaseKeyword;
case "default":
return SyntaxKind.DefaultKeyword;
case "lock":
return SyntaxKind.LockKeyword;
case "try":
return SyntaxKind.TryKeyword;
case "throw":
return SyntaxKind.ThrowKeyword;
case "catch":
return SyntaxKind.CatchKeyword;
case "finally":
return SyntaxKind.FinallyKeyword;
case "goto":
return SyntaxKind.GotoKeyword;
case "break":
return SyntaxKind.BreakKeyword;
case "continue":
return SyntaxKind.ContinueKeyword;
case "return":
return SyntaxKind.ReturnKeyword;
case "public":
return SyntaxKind.PublicKeyword;
case "private":
return SyntaxKind.PrivateKeyword;
case "internal":
return SyntaxKind.InternalKeyword;
case "protected":
return SyntaxKind.ProtectedKeyword;
case "static":
return SyntaxKind.StaticKeyword;
case "readonly":
return SyntaxKind.ReadOnlyKeyword;
case "sealed":
return SyntaxKind.SealedKeyword;
case "const":
return SyntaxKind.ConstKeyword;
case "fixed":
return SyntaxKind.FixedKeyword;
case "stackalloc":
return SyntaxKind.StackAllocKeyword;
case "volatile":
return SyntaxKind.VolatileKeyword;
case "new":
return SyntaxKind.NewKeyword;
case "override":
return SyntaxKind.OverrideKeyword;
case "abstract":
return SyntaxKind.AbstractKeyword;
case "virtual":
return SyntaxKind.VirtualKeyword;
case "event":
return SyntaxKind.EventKeyword;
case "extern":
return SyntaxKind.ExternKeyword;
case "ref":
return SyntaxKind.RefKeyword;
case "out":
return SyntaxKind.OutKeyword;
case "in":
return SyntaxKind.InKeyword;
case "is":
return SyntaxKind.IsKeyword;
case "as":
return SyntaxKind.AsKeyword;
case "params":
return SyntaxKind.ParamsKeyword;
case "__arglist":
return SyntaxKind.ArgListKeyword;
case "__makeref":
return SyntaxKind.MakeRefKeyword;
case "__reftype":
return SyntaxKind.RefTypeKeyword;
case "__refvalue":
return SyntaxKind.RefValueKeyword;
case "this":
return SyntaxKind.ThisKeyword;
case "base":
return SyntaxKind.BaseKeyword;
case "namespace":
return SyntaxKind.NamespaceKeyword;
case "using":
return SyntaxKind.UsingKeyword;
case "class":
return SyntaxKind.ClassKeyword;
case "struct":
return SyntaxKind.StructKeyword;
case "interface":
return SyntaxKind.InterfaceKeyword;
case "enum":
return SyntaxKind.EnumKeyword;
case "delegate":
return SyntaxKind.DelegateKeyword;
case "checked":
return SyntaxKind.CheckedKeyword;
case "unchecked":
return SyntaxKind.UncheckedKeyword;
case "unsafe":
return SyntaxKind.UnsafeKeyword;
case "operator":
return SyntaxKind.OperatorKeyword;
case "implicit":
return SyntaxKind.ImplicitKeyword;
case "explicit":
return SyntaxKind.ExplicitKeyword;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetOperatorKind(string operatorMetadataName)
{
switch (operatorMetadataName)
{
case WellKnownMemberNames.AdditionOperatorName: return SyntaxKind.PlusToken;
case WellKnownMemberNames.BitwiseAndOperatorName: return SyntaxKind.AmpersandToken;
case WellKnownMemberNames.BitwiseOrOperatorName: return SyntaxKind.BarToken;
// case WellKnownMemberNames.ConcatenateOperatorName:
case WellKnownMemberNames.DecrementOperatorName: return SyntaxKind.MinusMinusToken;
case WellKnownMemberNames.DivisionOperatorName: return SyntaxKind.SlashToken;
case WellKnownMemberNames.EqualityOperatorName: return SyntaxKind.EqualsEqualsToken;
case WellKnownMemberNames.ExclusiveOrOperatorName: return SyntaxKind.CaretToken;
case WellKnownMemberNames.ExplicitConversionName: return SyntaxKind.ExplicitKeyword;
// case WellKnownMemberNames.ExponentOperatorName:
case WellKnownMemberNames.FalseOperatorName: return SyntaxKind.FalseKeyword;
case WellKnownMemberNames.GreaterThanOperatorName: return SyntaxKind.GreaterThanToken;
case WellKnownMemberNames.GreaterThanOrEqualOperatorName: return SyntaxKind.GreaterThanEqualsToken;
case WellKnownMemberNames.ImplicitConversionName: return SyntaxKind.ImplicitKeyword;
case WellKnownMemberNames.IncrementOperatorName: return SyntaxKind.PlusPlusToken;
case WellKnownMemberNames.InequalityOperatorName: return SyntaxKind.ExclamationEqualsToken;
//case WellKnownMemberNames.IntegerDivisionOperatorName:
case WellKnownMemberNames.LeftShiftOperatorName: return SyntaxKind.LessThanLessThanToken;
case WellKnownMemberNames.LessThanOperatorName: return SyntaxKind.LessThanToken;
case WellKnownMemberNames.LessThanOrEqualOperatorName: return SyntaxKind.LessThanEqualsToken;
// case WellKnownMemberNames.LikeOperatorName:
case WellKnownMemberNames.LogicalNotOperatorName: return SyntaxKind.ExclamationToken;
case WellKnownMemberNames.ModulusOperatorName: return SyntaxKind.PercentToken;
case WellKnownMemberNames.MultiplyOperatorName: return SyntaxKind.AsteriskToken;
case WellKnownMemberNames.OnesComplementOperatorName: return SyntaxKind.TildeToken;
case WellKnownMemberNames.RightShiftOperatorName: return SyntaxKind.GreaterThanGreaterThanToken;
case WellKnownMemberNames.SubtractionOperatorName: return SyntaxKind.MinusToken;
case WellKnownMemberNames.TrueOperatorName: return SyntaxKind.TrueKeyword;
case WellKnownMemberNames.UnaryNegationOperatorName: return SyntaxKind.MinusToken;
case WellKnownMemberNames.UnaryPlusOperatorName: return SyntaxKind.PlusToken;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetPreprocessorKeywordKind(string text)
{
switch (text)
{
case "true":
return SyntaxKind.TrueKeyword;
case "false":
return SyntaxKind.FalseKeyword;
case "default":
return SyntaxKind.DefaultKeyword;
case "if":
return SyntaxKind.IfKeyword;
case "else":
return SyntaxKind.ElseKeyword;
case "elif":
return SyntaxKind.ElifKeyword;
case "endif":
return SyntaxKind.EndIfKeyword;
case "region":
return SyntaxKind.RegionKeyword;
case "endregion":
return SyntaxKind.EndRegionKeyword;
case "define":
return SyntaxKind.DefineKeyword;
case "undef":
return SyntaxKind.UndefKeyword;
case "warning":
return SyntaxKind.WarningKeyword;
case "error":
return SyntaxKind.ErrorKeyword;
case "line":
return SyntaxKind.LineKeyword;
case "pragma":
return SyntaxKind.PragmaKeyword;
case "hidden":
return SyntaxKind.HiddenKeyword;
case "checksum":
return SyntaxKind.ChecksumKeyword;
case "disable":
return SyntaxKind.DisableKeyword;
case "restore":
return SyntaxKind.RestoreKeyword;
case "r":
return SyntaxKind.ReferenceKeyword;
case "load":
return SyntaxKind.LoadKeyword;
case "nullable":
return SyntaxKind.NullableKeyword;
case "enable":
return SyntaxKind.EnableKeyword;
case "warnings":
return SyntaxKind.WarningsKeyword;
case "annotations":
return SyntaxKind.AnnotationsKeyword;
default:
return SyntaxKind.None;
}
}
public static IEnumerable<SyntaxKind> GetContextualKeywordKinds()
{
for (int i = (int)SyntaxKind.YieldKeyword; i <= (int)SyntaxKind.UnmanagedKeyword; i++)
{
yield return (SyntaxKind)i;
}
}
public static bool IsContextualKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.YieldKeyword:
case SyntaxKind.PartialKeyword:
case SyntaxKind.FromKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.IntoKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.SelectKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.AddKeyword:
case SyntaxKind.RemoveKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.AliasKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
case SyntaxKind.AssemblyKeyword:
case SyntaxKind.ModuleKeyword:
case SyntaxKind.TypeKeyword:
case SyntaxKind.GlobalKeyword:
case SyntaxKind.FieldKeyword:
case SyntaxKind.MethodKeyword:
case SyntaxKind.ParamKeyword:
case SyntaxKind.PropertyKeyword:
case SyntaxKind.TypeVarKeyword:
case SyntaxKind.NameOfKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.AwaitKeyword:
case SyntaxKind.WhenKeyword:
case SyntaxKind.UnderscoreToken:
case SyntaxKind.VarKeyword:
case SyntaxKind.OrKeyword:
case SyntaxKind.AndKeyword:
case SyntaxKind.NotKeyword:
case SyntaxKind.WithKeyword:
case SyntaxKind.InitKeyword:
case SyntaxKind.RecordKeyword:
case SyntaxKind.ManagedKeyword:
case SyntaxKind.UnmanagedKeyword:
return true;
default:
return false;
}
}
public static bool IsQueryContextualKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.FromKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.SelectKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.IntoKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.ByKeyword:
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return true;
default:
return false;
}
}
public static SyntaxKind GetContextualKeywordKind(string text)
{
switch (text)
{
case "yield":
return SyntaxKind.YieldKeyword;
case "partial":
return SyntaxKind.PartialKeyword;
case "from":
return SyntaxKind.FromKeyword;
case "group":
return SyntaxKind.GroupKeyword;
case "join":
return SyntaxKind.JoinKeyword;
case "into":
return SyntaxKind.IntoKeyword;
case "let":
return SyntaxKind.LetKeyword;
case "by":
return SyntaxKind.ByKeyword;
case "where":
return SyntaxKind.WhereKeyword;
case "select":
return SyntaxKind.SelectKeyword;
case "get":
return SyntaxKind.GetKeyword;
case "set":
return SyntaxKind.SetKeyword;
case "add":
return SyntaxKind.AddKeyword;
case "remove":
return SyntaxKind.RemoveKeyword;
case "orderby":
return SyntaxKind.OrderByKeyword;
case "alias":
return SyntaxKind.AliasKeyword;
case "on":
return SyntaxKind.OnKeyword;
case "equals":
return SyntaxKind.EqualsKeyword;
case "ascending":
return SyntaxKind.AscendingKeyword;
case "descending":
return SyntaxKind.DescendingKeyword;
case "assembly":
return SyntaxKind.AssemblyKeyword;
case "module":
return SyntaxKind.ModuleKeyword;
case "type":
return SyntaxKind.TypeKeyword;
case "field":
return SyntaxKind.FieldKeyword;
case "method":
return SyntaxKind.MethodKeyword;
case "param":
return SyntaxKind.ParamKeyword;
case "property":
return SyntaxKind.PropertyKeyword;
case "typevar":
return SyntaxKind.TypeVarKeyword;
case "global":
return SyntaxKind.GlobalKeyword;
case "async":
return SyntaxKind.AsyncKeyword;
case "await":
return SyntaxKind.AwaitKeyword;
case "when":
return SyntaxKind.WhenKeyword;
case "nameof":
return SyntaxKind.NameOfKeyword;
case "_":
return SyntaxKind.UnderscoreToken;
case "var":
return SyntaxKind.VarKeyword;
case "and":
return SyntaxKind.AndKeyword;
case "or":
return SyntaxKind.OrKeyword;
case "not":
return SyntaxKind.NotKeyword;
case "with":
return SyntaxKind.WithKeyword;
case "init":
return SyntaxKind.InitKeyword;
case "record":
return SyntaxKind.RecordKeyword;
case "managed":
return SyntaxKind.ManagedKeyword;
case "unmanaged":
return SyntaxKind.UnmanagedKeyword;
default:
return SyntaxKind.None;
}
}
public static string GetText(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TildeToken:
return "~";
case SyntaxKind.ExclamationToken:
return "!";
case SyntaxKind.DollarToken:
return "$";
case SyntaxKind.PercentToken:
return "%";
case SyntaxKind.CaretToken:
return "^";
case SyntaxKind.AmpersandToken:
return "&";
case SyntaxKind.AsteriskToken:
return "*";
case SyntaxKind.OpenParenToken:
return "(";
case SyntaxKind.CloseParenToken:
return ")";
case SyntaxKind.MinusToken:
return "-";
case SyntaxKind.PlusToken:
return "+";
case SyntaxKind.EqualsToken:
return "=";
case SyntaxKind.OpenBraceToken:
return "{";
case SyntaxKind.CloseBraceToken:
return "}";
case SyntaxKind.OpenBracketToken:
return "[";
case SyntaxKind.CloseBracketToken:
return "]";
case SyntaxKind.BarToken:
return "|";
case SyntaxKind.BackslashToken:
return "\\";
case SyntaxKind.ColonToken:
return ":";
case SyntaxKind.SemicolonToken:
return ";";
case SyntaxKind.DoubleQuoteToken:
return "\"";
case SyntaxKind.SingleQuoteToken:
return "'";
case SyntaxKind.LessThanToken:
return "<";
case SyntaxKind.CommaToken:
return ",";
case SyntaxKind.GreaterThanToken:
return ">";
case SyntaxKind.DotToken:
return ".";
case SyntaxKind.QuestionToken:
return "?";
case SyntaxKind.HashToken:
return "#";
case SyntaxKind.SlashToken:
return "/";
case SyntaxKind.SlashGreaterThanToken:
return "/>";
case SyntaxKind.LessThanSlashToken:
return "</";
case SyntaxKind.XmlCommentStartToken:
return "<!--";
case SyntaxKind.XmlCommentEndToken:
return "-->";
case SyntaxKind.XmlCDataStartToken:
return "<![CDATA[";
case SyntaxKind.XmlCDataEndToken:
return "]]>";
case SyntaxKind.XmlProcessingInstructionStartToken:
return "<?";
case SyntaxKind.XmlProcessingInstructionEndToken:
return "?>";
// compound
case SyntaxKind.BarBarToken:
return "||";
case SyntaxKind.AmpersandAmpersandToken:
return "&&";
case SyntaxKind.MinusMinusToken:
return "--";
case SyntaxKind.PlusPlusToken:
return "++";
case SyntaxKind.ColonColonToken:
return "::";
case SyntaxKind.QuestionQuestionToken:
return "??";
case SyntaxKind.MinusGreaterThanToken:
return "->";
case SyntaxKind.ExclamationEqualsToken:
return "!=";
case SyntaxKind.EqualsEqualsToken:
return "==";
case SyntaxKind.EqualsGreaterThanToken:
return "=>";
case SyntaxKind.LessThanEqualsToken:
return "<=";
case SyntaxKind.LessThanLessThanToken:
return "<<";
case SyntaxKind.LessThanLessThanEqualsToken:
return "<<=";
case SyntaxKind.GreaterThanEqualsToken:
return ">=";
case SyntaxKind.GreaterThanGreaterThanToken:
return ">>";
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return ">>=";
case SyntaxKind.SlashEqualsToken:
return "/=";
case SyntaxKind.AsteriskEqualsToken:
return "*=";
case SyntaxKind.BarEqualsToken:
return "|=";
case SyntaxKind.AmpersandEqualsToken:
return "&=";
case SyntaxKind.PlusEqualsToken:
return "+=";
case SyntaxKind.MinusEqualsToken:
return "-=";
case SyntaxKind.CaretEqualsToken:
return "^=";
case SyntaxKind.PercentEqualsToken:
return "%=";
case SyntaxKind.QuestionQuestionEqualsToken:
return "??=";
case SyntaxKind.DotDotToken:
return "..";
// Keywords
case SyntaxKind.BoolKeyword:
return "bool";
case SyntaxKind.ByteKeyword:
return "byte";
case SyntaxKind.SByteKeyword:
return "sbyte";
case SyntaxKind.ShortKeyword:
return "short";
case SyntaxKind.UShortKeyword:
return "ushort";
case SyntaxKind.IntKeyword:
return "int";
case SyntaxKind.UIntKeyword:
return "uint";
case SyntaxKind.LongKeyword:
return "long";
case SyntaxKind.ULongKeyword:
return "ulong";
case SyntaxKind.DoubleKeyword:
return "double";
case SyntaxKind.FloatKeyword:
return "float";
case SyntaxKind.DecimalKeyword:
return "decimal";
case SyntaxKind.StringKeyword:
return "string";
case SyntaxKind.CharKeyword:
return "char";
case SyntaxKind.VoidKeyword:
return "void";
case SyntaxKind.ObjectKeyword:
return "object";
case SyntaxKind.TypeOfKeyword:
return "typeof";
case SyntaxKind.SizeOfKeyword:
return "sizeof";
case SyntaxKind.NullKeyword:
return "null";
case SyntaxKind.TrueKeyword:
return "true";
case SyntaxKind.FalseKeyword:
return "false";
case SyntaxKind.IfKeyword:
return "if";
case SyntaxKind.ElseKeyword:
return "else";
case SyntaxKind.WhileKeyword:
return "while";
case SyntaxKind.ForKeyword:
return "for";
case SyntaxKind.ForEachKeyword:
return "foreach";
case SyntaxKind.DoKeyword:
return "do";
case SyntaxKind.SwitchKeyword:
return "switch";
case SyntaxKind.CaseKeyword:
return "case";
case SyntaxKind.DefaultKeyword:
return "default";
case SyntaxKind.TryKeyword:
return "try";
case SyntaxKind.CatchKeyword:
return "catch";
case SyntaxKind.FinallyKeyword:
return "finally";
case SyntaxKind.LockKeyword:
return "lock";
case SyntaxKind.GotoKeyword:
return "goto";
case SyntaxKind.BreakKeyword:
return "break";
case SyntaxKind.ContinueKeyword:
return "continue";
case SyntaxKind.ReturnKeyword:
return "return";
case SyntaxKind.ThrowKeyword:
return "throw";
case SyntaxKind.PublicKeyword:
return "public";
case SyntaxKind.PrivateKeyword:
return "private";
case SyntaxKind.InternalKeyword:
return "internal";
case SyntaxKind.ProtectedKeyword:
return "protected";
case SyntaxKind.StaticKeyword:
return "static";
case SyntaxKind.ReadOnlyKeyword:
return "readonly";
case SyntaxKind.SealedKeyword:
return "sealed";
case SyntaxKind.ConstKeyword:
return "const";
case SyntaxKind.FixedKeyword:
return "fixed";
case SyntaxKind.StackAllocKeyword:
return "stackalloc";
case SyntaxKind.VolatileKeyword:
return "volatile";
case SyntaxKind.NewKeyword:
return "new";
case SyntaxKind.OverrideKeyword:
return "override";
case SyntaxKind.AbstractKeyword:
return "abstract";
case SyntaxKind.VirtualKeyword:
return "virtual";
case SyntaxKind.EventKeyword:
return "event";
case SyntaxKind.ExternKeyword:
return "extern";
case SyntaxKind.RefKeyword:
return "ref";
case SyntaxKind.OutKeyword:
return "out";
case SyntaxKind.InKeyword:
return "in";
case SyntaxKind.IsKeyword:
return "is";
case SyntaxKind.AsKeyword:
return "as";
case SyntaxKind.ParamsKeyword:
return "params";
case SyntaxKind.ArgListKeyword:
return "__arglist";
case SyntaxKind.MakeRefKeyword:
return "__makeref";
case SyntaxKind.RefTypeKeyword:
return "__reftype";
case SyntaxKind.RefValueKeyword:
return "__refvalue";
case SyntaxKind.ThisKeyword:
return "this";
case SyntaxKind.BaseKeyword:
return "base";
case SyntaxKind.NamespaceKeyword:
return "namespace";
case SyntaxKind.UsingKeyword:
return "using";
case SyntaxKind.ClassKeyword:
return "class";
case SyntaxKind.StructKeyword:
return "struct";
case SyntaxKind.InterfaceKeyword:
return "interface";
case SyntaxKind.EnumKeyword:
return "enum";
case SyntaxKind.DelegateKeyword:
return "delegate";
case SyntaxKind.CheckedKeyword:
return "checked";
case SyntaxKind.UncheckedKeyword:
return "unchecked";
case SyntaxKind.UnsafeKeyword:
return "unsafe";
case SyntaxKind.OperatorKeyword:
return "operator";
case SyntaxKind.ImplicitKeyword:
return "implicit";
case SyntaxKind.ExplicitKeyword:
return "explicit";
case SyntaxKind.ElifKeyword:
return "elif";
case SyntaxKind.EndIfKeyword:
return "endif";
case SyntaxKind.RegionKeyword:
return "region";
case SyntaxKind.EndRegionKeyword:
return "endregion";
case SyntaxKind.DefineKeyword:
return "define";
case SyntaxKind.UndefKeyword:
return "undef";
case SyntaxKind.WarningKeyword:
return "warning";
case SyntaxKind.ErrorKeyword:
return "error";
case SyntaxKind.LineKeyword:
return "line";
case SyntaxKind.PragmaKeyword:
return "pragma";
case SyntaxKind.HiddenKeyword:
return "hidden";
case SyntaxKind.ChecksumKeyword:
return "checksum";
case SyntaxKind.DisableKeyword:
return "disable";
case SyntaxKind.RestoreKeyword:
return "restore";
case SyntaxKind.ReferenceKeyword:
return "r";
case SyntaxKind.LoadKeyword:
return "load";
case SyntaxKind.NullableKeyword:
return "nullable";
case SyntaxKind.EnableKeyword:
return "enable";
case SyntaxKind.WarningsKeyword:
return "warnings";
case SyntaxKind.AnnotationsKeyword:
return "annotations";
// contextual keywords
case SyntaxKind.YieldKeyword:
return "yield";
case SyntaxKind.PartialKeyword:
return "partial";
case SyntaxKind.FromKeyword:
return "from";
case SyntaxKind.GroupKeyword:
return "group";
case SyntaxKind.JoinKeyword:
return "join";
case SyntaxKind.IntoKeyword:
return "into";
case SyntaxKind.LetKeyword:
return "let";
case SyntaxKind.ByKeyword:
return "by";
case SyntaxKind.WhereKeyword:
return "where";
case SyntaxKind.SelectKeyword:
return "select";
case SyntaxKind.GetKeyword:
return "get";
case SyntaxKind.SetKeyword:
return "set";
case SyntaxKind.AddKeyword:
return "add";
case SyntaxKind.RemoveKeyword:
return "remove";
case SyntaxKind.OrderByKeyword:
return "orderby";
case SyntaxKind.AliasKeyword:
return "alias";
case SyntaxKind.OnKeyword:
return "on";
case SyntaxKind.EqualsKeyword:
return "equals";
case SyntaxKind.AscendingKeyword:
return "ascending";
case SyntaxKind.DescendingKeyword:
return "descending";
case SyntaxKind.AssemblyKeyword:
return "assembly";
case SyntaxKind.ModuleKeyword:
return "module";
case SyntaxKind.TypeKeyword:
return "type";
case SyntaxKind.FieldKeyword:
return "field";
case SyntaxKind.MethodKeyword:
return "method";
case SyntaxKind.ParamKeyword:
return "param";
case SyntaxKind.PropertyKeyword:
return "property";
case SyntaxKind.TypeVarKeyword:
return "typevar";
case SyntaxKind.GlobalKeyword:
return "global";
case SyntaxKind.NameOfKeyword:
return "nameof";
case SyntaxKind.AsyncKeyword:
return "async";
case SyntaxKind.AwaitKeyword:
return "await";
case SyntaxKind.WhenKeyword:
return "when";
case SyntaxKind.InterpolatedStringStartToken:
return "$\"";
case SyntaxKind.InterpolatedStringEndToken:
return "\"";
case SyntaxKind.InterpolatedVerbatimStringStartToken:
return "$@\"";
case SyntaxKind.UnderscoreToken:
return "_";
case SyntaxKind.VarKeyword:
return "var";
case SyntaxKind.AndKeyword:
return "and";
case SyntaxKind.OrKeyword:
return "or";
case SyntaxKind.NotKeyword:
return "not";
case SyntaxKind.WithKeyword:
return "with";
case SyntaxKind.InitKeyword:
return "init";
case SyntaxKind.RecordKeyword:
return "record";
case SyntaxKind.ManagedKeyword:
return "managed";
case SyntaxKind.UnmanagedKeyword:
return "unmanaged";
default:
return string.Empty;
}
}
public static bool IsTypeParameterVarianceKeyword(SyntaxKind kind)
{
return kind == SyntaxKind.OutKeyword || kind == SyntaxKind.InKeyword;
}
public static bool IsDocumentationCommentTrivia(SyntaxKind kind)
{
return kind == SyntaxKind.SingleLineDocumentationCommentTrivia ||
kind == SyntaxKind.MultiLineDocumentationCommentTrivia;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CSharp
{
public static partial class SyntaxFacts
{
public static bool IsKeywordKind(SyntaxKind kind)
{
return IsReservedKeyword(kind) || IsContextualKeyword(kind);
}
public static IEnumerable<SyntaxKind> GetReservedKeywordKinds()
{
for (int i = (int)SyntaxKind.BoolKeyword; i <= (int)SyntaxKind.ImplicitKeyword; i++)
{
yield return (SyntaxKind)i;
}
}
public static IEnumerable<SyntaxKind> GetKeywordKinds()
{
foreach (var reserved in GetReservedKeywordKinds())
{
yield return reserved;
}
foreach (var contextual in GetContextualKeywordKinds())
{
yield return contextual;
}
}
public static bool IsReservedKeyword(SyntaxKind kind)
{
return kind >= SyntaxKind.BoolKeyword && kind <= SyntaxKind.ImplicitKeyword;
}
public static bool IsAttributeTargetSpecifier(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.AssemblyKeyword:
case SyntaxKind.ModuleKeyword:
return true;
default:
return false;
}
}
public static bool IsAccessibilityModifier(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.PublicKeyword:
return true;
default:
return false;
}
}
public static bool IsPreprocessorKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.IfKeyword:
case SyntaxKind.ElseKeyword:
case SyntaxKind.ElifKeyword:
case SyntaxKind.EndIfKeyword:
case SyntaxKind.RegionKeyword:
case SyntaxKind.EndRegionKeyword:
case SyntaxKind.DefineKeyword:
case SyntaxKind.UndefKeyword:
case SyntaxKind.WarningKeyword:
case SyntaxKind.ErrorKeyword:
case SyntaxKind.LineKeyword:
case SyntaxKind.PragmaKeyword:
case SyntaxKind.HiddenKeyword:
case SyntaxKind.ChecksumKeyword:
case SyntaxKind.DisableKeyword:
case SyntaxKind.RestoreKeyword:
case SyntaxKind.ReferenceKeyword:
case SyntaxKind.LoadKeyword:
case SyntaxKind.NullableKeyword:
case SyntaxKind.EnableKeyword:
case SyntaxKind.WarningsKeyword:
case SyntaxKind.AnnotationsKeyword:
return true;
default:
return false;
}
}
/// <summary>
/// Some preprocessor keywords are only keywords when they appear after a
/// hash sign (#). For these keywords, the lexer will produce tokens with
/// Kind = SyntaxKind.IdentifierToken and ContextualKind set to the keyword
/// SyntaxKind.
/// </summary>
/// <remarks>
/// This wrinkle is specifically not publicly exposed.
/// </remarks>
internal static bool IsPreprocessorContextualKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.HiddenKeyword:
case SyntaxKind.ChecksumKeyword:
case SyntaxKind.DisableKeyword:
case SyntaxKind.RestoreKeyword:
case SyntaxKind.EnableKeyword:
case SyntaxKind.WarningsKeyword:
case SyntaxKind.AnnotationsKeyword:
return false;
default:
return IsPreprocessorKeyword(kind);
}
}
public static IEnumerable<SyntaxKind> GetPreprocessorKeywordKinds()
{
yield return SyntaxKind.TrueKeyword;
yield return SyntaxKind.FalseKeyword;
yield return SyntaxKind.DefaultKeyword;
yield return SyntaxKind.HiddenKeyword;
for (int i = (int)SyntaxKind.ElifKeyword; i <= (int)SyntaxKind.RestoreKeyword; i++)
{
yield return (SyntaxKind)i;
}
}
public static bool IsPunctuation(SyntaxKind kind)
{
return kind >= SyntaxKind.TildeToken && kind <= SyntaxKind.QuestionQuestionEqualsToken;
}
public static bool IsLanguagePunctuation(SyntaxKind kind)
{
return IsPunctuation(kind) && !IsPreprocessorKeyword(kind) && !IsDebuggerSpecialPunctuation(kind);
}
public static bool IsPreprocessorPunctuation(SyntaxKind kind)
{
return kind == SyntaxKind.HashToken;
}
private static bool IsDebuggerSpecialPunctuation(SyntaxKind kind)
{
// TODO: What about "<>f_AnonymousMethod"? Or "123#"? What's this used for?
return kind == SyntaxKind.DollarToken;
}
public static IEnumerable<SyntaxKind> GetPunctuationKinds()
{
for (int i = (int)SyntaxKind.TildeToken; i <= (int)SyntaxKind.PercentEqualsToken; i++)
{
yield return (SyntaxKind)i;
}
}
public static bool IsPunctuationOrKeyword(SyntaxKind kind)
{
return kind >= SyntaxKind.TildeToken && kind <= SyntaxKind.EndOfFileToken;
}
internal static bool IsLiteral(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.IdentifierToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.XmlTextLiteralToken:
case SyntaxKind.XmlTextLiteralNewLineToken:
case SyntaxKind.XmlEntityLiteralToken:
//case SyntaxKind.Unknown:
return true;
default:
return false;
}
}
public static bool IsAnyToken(SyntaxKind kind)
{
if (kind >= SyntaxKind.TildeToken && kind < SyntaxKind.EndOfLineTrivia) return true;
switch (kind)
{
case SyntaxKind.InterpolatedStringToken:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.LoadKeyword:
case SyntaxKind.NullableKeyword:
case SyntaxKind.EnableKeyword:
case SyntaxKind.UnderscoreToken:
return true;
default:
return false;
}
}
public static bool IsTrivia(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.EndOfLineTrivia:
case SyntaxKind.WhitespaceTrivia:
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineDocumentationCommentTrivia:
case SyntaxKind.MultiLineDocumentationCommentTrivia:
case SyntaxKind.DisabledTextTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
case SyntaxKind.ConflictMarkerTrivia:
return true;
default:
return IsPreprocessorDirective(kind);
}
}
public static bool IsPreprocessorDirective(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.IfDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.EndIfDirectiveTrivia:
case SyntaxKind.RegionDirectiveTrivia:
case SyntaxKind.EndRegionDirectiveTrivia:
case SyntaxKind.DefineDirectiveTrivia:
case SyntaxKind.UndefDirectiveTrivia:
case SyntaxKind.ErrorDirectiveTrivia:
case SyntaxKind.WarningDirectiveTrivia:
case SyntaxKind.LineDirectiveTrivia:
case SyntaxKind.LineSpanDirectiveTrivia:
case SyntaxKind.PragmaWarningDirectiveTrivia:
case SyntaxKind.PragmaChecksumDirectiveTrivia:
case SyntaxKind.ReferenceDirectiveTrivia:
case SyntaxKind.LoadDirectiveTrivia:
case SyntaxKind.BadDirectiveTrivia:
case SyntaxKind.ShebangDirectiveTrivia:
case SyntaxKind.NullableDirectiveTrivia:
return true;
default:
return false;
}
}
public static bool IsName(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.QualifiedName:
case SyntaxKind.AliasQualifiedName:
return true;
default:
return false;
}
}
public static bool IsPredefinedType(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.BoolKeyword:
case SyntaxKind.ByteKeyword:
case SyntaxKind.SByteKeyword:
case SyntaxKind.IntKeyword:
case SyntaxKind.UIntKeyword:
case SyntaxKind.ShortKeyword:
case SyntaxKind.UShortKeyword:
case SyntaxKind.LongKeyword:
case SyntaxKind.ULongKeyword:
case SyntaxKind.FloatKeyword:
case SyntaxKind.DoubleKeyword:
case SyntaxKind.DecimalKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.CharKeyword:
case SyntaxKind.ObjectKeyword:
case SyntaxKind.VoidKeyword:
return true;
default:
return false;
}
}
public static bool IsTypeSyntax(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ArrayType:
case SyntaxKind.PointerType:
case SyntaxKind.NullableType:
case SyntaxKind.PredefinedType:
case SyntaxKind.TupleType:
case SyntaxKind.FunctionPointerType:
return true;
default:
return IsName(kind);
}
}
/// <summary>
/// Member declarations that can appear in global code (other than type declarations).
/// </summary>
public static bool IsGlobalMemberDeclaration(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.GlobalStatement:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
return true;
}
return false;
}
public static bool IsTypeDeclaration(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
return true;
default:
return false;
}
}
public static bool IsNamespaceMemberDeclaration(SyntaxKind kind)
=> IsTypeDeclaration(kind) ||
kind == SyntaxKind.NamespaceDeclaration ||
kind == SyntaxKind.FileScopedNamespaceDeclaration;
public static bool IsAnyUnaryExpression(SyntaxKind token)
{
return IsPrefixUnaryExpression(token) || IsPostfixUnaryExpression(token);
}
public static bool IsPrefixUnaryExpression(SyntaxKind token)
{
return GetPrefixUnaryExpression(token) != SyntaxKind.None;
}
public static bool IsPrefixUnaryExpressionOperatorToken(SyntaxKind token)
{
return GetPrefixUnaryExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetPrefixUnaryExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.PlusToken:
return SyntaxKind.UnaryPlusExpression;
case SyntaxKind.MinusToken:
return SyntaxKind.UnaryMinusExpression;
case SyntaxKind.TildeToken:
return SyntaxKind.BitwiseNotExpression;
case SyntaxKind.ExclamationToken:
return SyntaxKind.LogicalNotExpression;
case SyntaxKind.PlusPlusToken:
return SyntaxKind.PreIncrementExpression;
case SyntaxKind.MinusMinusToken:
return SyntaxKind.PreDecrementExpression;
case SyntaxKind.AmpersandToken:
return SyntaxKind.AddressOfExpression;
case SyntaxKind.AsteriskToken:
return SyntaxKind.PointerIndirectionExpression;
case SyntaxKind.CaretToken:
return SyntaxKind.IndexExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsPostfixUnaryExpression(SyntaxKind token)
{
return GetPostfixUnaryExpression(token) != SyntaxKind.None;
}
public static bool IsPostfixUnaryExpressionToken(SyntaxKind token)
{
return GetPostfixUnaryExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetPostfixUnaryExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.PlusPlusToken:
return SyntaxKind.PostIncrementExpression;
case SyntaxKind.MinusMinusToken:
return SyntaxKind.PostDecrementExpression;
case SyntaxKind.ExclamationToken:
return SyntaxKind.SuppressNullableWarningExpression;
default:
return SyntaxKind.None;
}
}
internal static bool IsIncrementOrDecrementOperator(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
return true;
default:
return false;
}
}
public static bool IsUnaryOperatorDeclarationToken(SyntaxKind token)
{
return IsPrefixUnaryExpressionOperatorToken(token) ||
token == SyntaxKind.TrueKeyword ||
token == SyntaxKind.FalseKeyword;
}
public static bool IsAnyOverloadableOperator(SyntaxKind kind)
{
return IsOverloadableBinaryOperator(kind) || IsOverloadableUnaryOperator(kind);
}
public static bool IsOverloadableBinaryOperator(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.AsteriskToken:
case SyntaxKind.SlashToken:
case SyntaxKind.PercentToken:
case SyntaxKind.CaretToken:
case SyntaxKind.AmpersandToken:
case SyntaxKind.BarToken:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.LessThanEqualsToken:
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.GreaterThanToken:
case SyntaxKind.GreaterThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.ExclamationEqualsToken:
return true;
default:
return false;
}
}
public static bool IsOverloadableUnaryOperator(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.TildeToken:
case SyntaxKind.ExclamationToken:
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
return true;
default:
return false;
}
}
public static bool IsPrimaryFunction(SyntaxKind keyword)
{
return GetPrimaryFunction(keyword) != SyntaxKind.None;
}
public static SyntaxKind GetPrimaryFunction(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.MakeRefKeyword:
return SyntaxKind.MakeRefExpression;
case SyntaxKind.RefTypeKeyword:
return SyntaxKind.RefTypeExpression;
case SyntaxKind.RefValueKeyword:
return SyntaxKind.RefValueExpression;
case SyntaxKind.CheckedKeyword:
return SyntaxKind.CheckedExpression;
case SyntaxKind.UncheckedKeyword:
return SyntaxKind.UncheckedExpression;
case SyntaxKind.DefaultKeyword:
return SyntaxKind.DefaultExpression;
case SyntaxKind.TypeOfKeyword:
return SyntaxKind.TypeOfExpression;
case SyntaxKind.SizeOfKeyword:
return SyntaxKind.SizeOfExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsLiteralExpression(SyntaxKind token)
{
return GetLiteralExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetLiteralExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.StringLiteralToken:
return SyntaxKind.StringLiteralExpression;
case SyntaxKind.CharacterLiteralToken:
return SyntaxKind.CharacterLiteralExpression;
case SyntaxKind.NumericLiteralToken:
return SyntaxKind.NumericLiteralExpression;
case SyntaxKind.NullKeyword:
return SyntaxKind.NullLiteralExpression;
case SyntaxKind.TrueKeyword:
return SyntaxKind.TrueLiteralExpression;
case SyntaxKind.FalseKeyword:
return SyntaxKind.FalseLiteralExpression;
case SyntaxKind.ArgListKeyword:
return SyntaxKind.ArgListExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsInstanceExpression(SyntaxKind token)
{
return GetInstanceExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetInstanceExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.ThisKeyword:
return SyntaxKind.ThisExpression;
case SyntaxKind.BaseKeyword:
return SyntaxKind.BaseExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsBinaryExpression(SyntaxKind token)
{
return GetBinaryExpression(token) != SyntaxKind.None;
}
public static bool IsBinaryExpressionOperatorToken(SyntaxKind token)
{
return GetBinaryExpression(token) != SyntaxKind.None;
}
public static SyntaxKind GetBinaryExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.QuestionQuestionToken:
return SyntaxKind.CoalesceExpression;
case SyntaxKind.IsKeyword:
return SyntaxKind.IsExpression;
case SyntaxKind.AsKeyword:
return SyntaxKind.AsExpression;
case SyntaxKind.BarToken:
return SyntaxKind.BitwiseOrExpression;
case SyntaxKind.CaretToken:
return SyntaxKind.ExclusiveOrExpression;
case SyntaxKind.AmpersandToken:
return SyntaxKind.BitwiseAndExpression;
case SyntaxKind.EqualsEqualsToken:
return SyntaxKind.EqualsExpression;
case SyntaxKind.ExclamationEqualsToken:
return SyntaxKind.NotEqualsExpression;
case SyntaxKind.LessThanToken:
return SyntaxKind.LessThanExpression;
case SyntaxKind.LessThanEqualsToken:
return SyntaxKind.LessThanOrEqualExpression;
case SyntaxKind.GreaterThanToken:
return SyntaxKind.GreaterThanExpression;
case SyntaxKind.GreaterThanEqualsToken:
return SyntaxKind.GreaterThanOrEqualExpression;
case SyntaxKind.LessThanLessThanToken:
return SyntaxKind.LeftShiftExpression;
case SyntaxKind.GreaterThanGreaterThanToken:
return SyntaxKind.RightShiftExpression;
case SyntaxKind.PlusToken:
return SyntaxKind.AddExpression;
case SyntaxKind.MinusToken:
return SyntaxKind.SubtractExpression;
case SyntaxKind.AsteriskToken:
return SyntaxKind.MultiplyExpression;
case SyntaxKind.SlashToken:
return SyntaxKind.DivideExpression;
case SyntaxKind.PercentToken:
return SyntaxKind.ModuloExpression;
case SyntaxKind.AmpersandAmpersandToken:
return SyntaxKind.LogicalAndExpression;
case SyntaxKind.BarBarToken:
return SyntaxKind.LogicalOrExpression;
default:
return SyntaxKind.None;
}
}
public static bool IsAssignmentExpression(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.CoalesceAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.SimpleAssignmentExpression:
return true;
default:
return false;
}
}
public static bool IsAssignmentExpressionOperatorToken(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.QuestionQuestionEqualsToken:
case SyntaxKind.BarEqualsToken:
case SyntaxKind.AmpersandEqualsToken:
case SyntaxKind.CaretEqualsToken:
case SyntaxKind.LessThanLessThanEqualsToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
case SyntaxKind.PlusEqualsToken:
case SyntaxKind.MinusEqualsToken:
case SyntaxKind.AsteriskEqualsToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.PercentEqualsToken:
case SyntaxKind.EqualsToken:
return true;
default:
return false;
}
}
public static SyntaxKind GetAssignmentExpression(SyntaxKind token)
{
switch (token)
{
case SyntaxKind.BarEqualsToken:
return SyntaxKind.OrAssignmentExpression;
case SyntaxKind.AmpersandEqualsToken:
return SyntaxKind.AndAssignmentExpression;
case SyntaxKind.CaretEqualsToken:
return SyntaxKind.ExclusiveOrAssignmentExpression;
case SyntaxKind.LessThanLessThanEqualsToken:
return SyntaxKind.LeftShiftAssignmentExpression;
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return SyntaxKind.RightShiftAssignmentExpression;
case SyntaxKind.PlusEqualsToken:
return SyntaxKind.AddAssignmentExpression;
case SyntaxKind.MinusEqualsToken:
return SyntaxKind.SubtractAssignmentExpression;
case SyntaxKind.AsteriskEqualsToken:
return SyntaxKind.MultiplyAssignmentExpression;
case SyntaxKind.SlashEqualsToken:
return SyntaxKind.DivideAssignmentExpression;
case SyntaxKind.PercentEqualsToken:
return SyntaxKind.ModuloAssignmentExpression;
case SyntaxKind.EqualsToken:
return SyntaxKind.SimpleAssignmentExpression;
case SyntaxKind.QuestionQuestionEqualsToken:
return SyntaxKind.CoalesceAssignmentExpression;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetCheckStatement(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.CheckedKeyword:
return SyntaxKind.CheckedStatement;
case SyntaxKind.UncheckedKeyword:
return SyntaxKind.UncheckedStatement;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetAccessorDeclarationKind(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.GetKeyword:
return SyntaxKind.GetAccessorDeclaration;
case SyntaxKind.SetKeyword:
return SyntaxKind.SetAccessorDeclaration;
case SyntaxKind.InitKeyword:
return SyntaxKind.InitAccessorDeclaration;
case SyntaxKind.AddKeyword:
return SyntaxKind.AddAccessorDeclaration;
case SyntaxKind.RemoveKeyword:
return SyntaxKind.RemoveAccessorDeclaration;
default:
return SyntaxKind.None;
}
}
public static bool IsAccessorDeclaration(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
default:
return false;
}
}
public static bool IsAccessorDeclarationKeyword(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.InitKeyword:
case SyntaxKind.AddKeyword:
case SyntaxKind.RemoveKeyword:
return true;
default:
return false;
}
}
public static SyntaxKind GetSwitchLabelKind(SyntaxKind keyword)
{
switch (keyword)
{
case SyntaxKind.CaseKeyword:
return SyntaxKind.CaseSwitchLabel;
case SyntaxKind.DefaultKeyword:
return SyntaxKind.DefaultSwitchLabel;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetBaseTypeDeclarationKind(SyntaxKind kind)
{
return kind == SyntaxKind.EnumKeyword ? SyntaxKind.EnumDeclaration : GetTypeDeclarationKind(kind);
}
public static SyntaxKind GetTypeDeclarationKind(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.ClassKeyword:
return SyntaxKind.ClassDeclaration;
case SyntaxKind.StructKeyword:
return SyntaxKind.StructDeclaration;
case SyntaxKind.InterfaceKeyword:
return SyntaxKind.InterfaceDeclaration;
case SyntaxKind.RecordKeyword:
return SyntaxKind.RecordDeclaration;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetKeywordKind(string text)
{
switch (text)
{
case "bool":
return SyntaxKind.BoolKeyword;
case "byte":
return SyntaxKind.ByteKeyword;
case "sbyte":
return SyntaxKind.SByteKeyword;
case "short":
return SyntaxKind.ShortKeyword;
case "ushort":
return SyntaxKind.UShortKeyword;
case "int":
return SyntaxKind.IntKeyword;
case "uint":
return SyntaxKind.UIntKeyword;
case "long":
return SyntaxKind.LongKeyword;
case "ulong":
return SyntaxKind.ULongKeyword;
case "double":
return SyntaxKind.DoubleKeyword;
case "float":
return SyntaxKind.FloatKeyword;
case "decimal":
return SyntaxKind.DecimalKeyword;
case "string":
return SyntaxKind.StringKeyword;
case "char":
return SyntaxKind.CharKeyword;
case "void":
return SyntaxKind.VoidKeyword;
case "object":
return SyntaxKind.ObjectKeyword;
case "typeof":
return SyntaxKind.TypeOfKeyword;
case "sizeof":
return SyntaxKind.SizeOfKeyword;
case "null":
return SyntaxKind.NullKeyword;
case "true":
return SyntaxKind.TrueKeyword;
case "false":
return SyntaxKind.FalseKeyword;
case "if":
return SyntaxKind.IfKeyword;
case "else":
return SyntaxKind.ElseKeyword;
case "while":
return SyntaxKind.WhileKeyword;
case "for":
return SyntaxKind.ForKeyword;
case "foreach":
return SyntaxKind.ForEachKeyword;
case "do":
return SyntaxKind.DoKeyword;
case "switch":
return SyntaxKind.SwitchKeyword;
case "case":
return SyntaxKind.CaseKeyword;
case "default":
return SyntaxKind.DefaultKeyword;
case "lock":
return SyntaxKind.LockKeyword;
case "try":
return SyntaxKind.TryKeyword;
case "throw":
return SyntaxKind.ThrowKeyword;
case "catch":
return SyntaxKind.CatchKeyword;
case "finally":
return SyntaxKind.FinallyKeyword;
case "goto":
return SyntaxKind.GotoKeyword;
case "break":
return SyntaxKind.BreakKeyword;
case "continue":
return SyntaxKind.ContinueKeyword;
case "return":
return SyntaxKind.ReturnKeyword;
case "public":
return SyntaxKind.PublicKeyword;
case "private":
return SyntaxKind.PrivateKeyword;
case "internal":
return SyntaxKind.InternalKeyword;
case "protected":
return SyntaxKind.ProtectedKeyword;
case "static":
return SyntaxKind.StaticKeyword;
case "readonly":
return SyntaxKind.ReadOnlyKeyword;
case "sealed":
return SyntaxKind.SealedKeyword;
case "const":
return SyntaxKind.ConstKeyword;
case "fixed":
return SyntaxKind.FixedKeyword;
case "stackalloc":
return SyntaxKind.StackAllocKeyword;
case "volatile":
return SyntaxKind.VolatileKeyword;
case "new":
return SyntaxKind.NewKeyword;
case "override":
return SyntaxKind.OverrideKeyword;
case "abstract":
return SyntaxKind.AbstractKeyword;
case "virtual":
return SyntaxKind.VirtualKeyword;
case "event":
return SyntaxKind.EventKeyword;
case "extern":
return SyntaxKind.ExternKeyword;
case "ref":
return SyntaxKind.RefKeyword;
case "out":
return SyntaxKind.OutKeyword;
case "in":
return SyntaxKind.InKeyword;
case "is":
return SyntaxKind.IsKeyword;
case "as":
return SyntaxKind.AsKeyword;
case "params":
return SyntaxKind.ParamsKeyword;
case "__arglist":
return SyntaxKind.ArgListKeyword;
case "__makeref":
return SyntaxKind.MakeRefKeyword;
case "__reftype":
return SyntaxKind.RefTypeKeyword;
case "__refvalue":
return SyntaxKind.RefValueKeyword;
case "this":
return SyntaxKind.ThisKeyword;
case "base":
return SyntaxKind.BaseKeyword;
case "namespace":
return SyntaxKind.NamespaceKeyword;
case "using":
return SyntaxKind.UsingKeyword;
case "class":
return SyntaxKind.ClassKeyword;
case "struct":
return SyntaxKind.StructKeyword;
case "interface":
return SyntaxKind.InterfaceKeyword;
case "enum":
return SyntaxKind.EnumKeyword;
case "delegate":
return SyntaxKind.DelegateKeyword;
case "checked":
return SyntaxKind.CheckedKeyword;
case "unchecked":
return SyntaxKind.UncheckedKeyword;
case "unsafe":
return SyntaxKind.UnsafeKeyword;
case "operator":
return SyntaxKind.OperatorKeyword;
case "implicit":
return SyntaxKind.ImplicitKeyword;
case "explicit":
return SyntaxKind.ExplicitKeyword;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetOperatorKind(string operatorMetadataName)
{
switch (operatorMetadataName)
{
case WellKnownMemberNames.AdditionOperatorName: return SyntaxKind.PlusToken;
case WellKnownMemberNames.BitwiseAndOperatorName: return SyntaxKind.AmpersandToken;
case WellKnownMemberNames.BitwiseOrOperatorName: return SyntaxKind.BarToken;
// case WellKnownMemberNames.ConcatenateOperatorName:
case WellKnownMemberNames.DecrementOperatorName: return SyntaxKind.MinusMinusToken;
case WellKnownMemberNames.DivisionOperatorName: return SyntaxKind.SlashToken;
case WellKnownMemberNames.EqualityOperatorName: return SyntaxKind.EqualsEqualsToken;
case WellKnownMemberNames.ExclusiveOrOperatorName: return SyntaxKind.CaretToken;
case WellKnownMemberNames.ExplicitConversionName: return SyntaxKind.ExplicitKeyword;
// case WellKnownMemberNames.ExponentOperatorName:
case WellKnownMemberNames.FalseOperatorName: return SyntaxKind.FalseKeyword;
case WellKnownMemberNames.GreaterThanOperatorName: return SyntaxKind.GreaterThanToken;
case WellKnownMemberNames.GreaterThanOrEqualOperatorName: return SyntaxKind.GreaterThanEqualsToken;
case WellKnownMemberNames.ImplicitConversionName: return SyntaxKind.ImplicitKeyword;
case WellKnownMemberNames.IncrementOperatorName: return SyntaxKind.PlusPlusToken;
case WellKnownMemberNames.InequalityOperatorName: return SyntaxKind.ExclamationEqualsToken;
//case WellKnownMemberNames.IntegerDivisionOperatorName:
case WellKnownMemberNames.LeftShiftOperatorName: return SyntaxKind.LessThanLessThanToken;
case WellKnownMemberNames.LessThanOperatorName: return SyntaxKind.LessThanToken;
case WellKnownMemberNames.LessThanOrEqualOperatorName: return SyntaxKind.LessThanEqualsToken;
// case WellKnownMemberNames.LikeOperatorName:
case WellKnownMemberNames.LogicalNotOperatorName: return SyntaxKind.ExclamationToken;
case WellKnownMemberNames.ModulusOperatorName: return SyntaxKind.PercentToken;
case WellKnownMemberNames.MultiplyOperatorName: return SyntaxKind.AsteriskToken;
case WellKnownMemberNames.OnesComplementOperatorName: return SyntaxKind.TildeToken;
case WellKnownMemberNames.RightShiftOperatorName: return SyntaxKind.GreaterThanGreaterThanToken;
case WellKnownMemberNames.SubtractionOperatorName: return SyntaxKind.MinusToken;
case WellKnownMemberNames.TrueOperatorName: return SyntaxKind.TrueKeyword;
case WellKnownMemberNames.UnaryNegationOperatorName: return SyntaxKind.MinusToken;
case WellKnownMemberNames.UnaryPlusOperatorName: return SyntaxKind.PlusToken;
default:
return SyntaxKind.None;
}
}
public static SyntaxKind GetPreprocessorKeywordKind(string text)
{
switch (text)
{
case "true":
return SyntaxKind.TrueKeyword;
case "false":
return SyntaxKind.FalseKeyword;
case "default":
return SyntaxKind.DefaultKeyword;
case "if":
return SyntaxKind.IfKeyword;
case "else":
return SyntaxKind.ElseKeyword;
case "elif":
return SyntaxKind.ElifKeyword;
case "endif":
return SyntaxKind.EndIfKeyword;
case "region":
return SyntaxKind.RegionKeyword;
case "endregion":
return SyntaxKind.EndRegionKeyword;
case "define":
return SyntaxKind.DefineKeyword;
case "undef":
return SyntaxKind.UndefKeyword;
case "warning":
return SyntaxKind.WarningKeyword;
case "error":
return SyntaxKind.ErrorKeyword;
case "line":
return SyntaxKind.LineKeyword;
case "pragma":
return SyntaxKind.PragmaKeyword;
case "hidden":
return SyntaxKind.HiddenKeyword;
case "checksum":
return SyntaxKind.ChecksumKeyword;
case "disable":
return SyntaxKind.DisableKeyword;
case "restore":
return SyntaxKind.RestoreKeyword;
case "r":
return SyntaxKind.ReferenceKeyword;
case "load":
return SyntaxKind.LoadKeyword;
case "nullable":
return SyntaxKind.NullableKeyword;
case "enable":
return SyntaxKind.EnableKeyword;
case "warnings":
return SyntaxKind.WarningsKeyword;
case "annotations":
return SyntaxKind.AnnotationsKeyword;
default:
return SyntaxKind.None;
}
}
public static IEnumerable<SyntaxKind> GetContextualKeywordKinds()
{
for (int i = (int)SyntaxKind.YieldKeyword; i <= (int)SyntaxKind.UnmanagedKeyword; i++)
{
yield return (SyntaxKind)i;
}
}
public static bool IsContextualKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.YieldKeyword:
case SyntaxKind.PartialKeyword:
case SyntaxKind.FromKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.IntoKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.SelectKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.AddKeyword:
case SyntaxKind.RemoveKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.AliasKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
case SyntaxKind.AssemblyKeyword:
case SyntaxKind.ModuleKeyword:
case SyntaxKind.TypeKeyword:
case SyntaxKind.GlobalKeyword:
case SyntaxKind.FieldKeyword:
case SyntaxKind.MethodKeyword:
case SyntaxKind.ParamKeyword:
case SyntaxKind.PropertyKeyword:
case SyntaxKind.TypeVarKeyword:
case SyntaxKind.NameOfKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.AwaitKeyword:
case SyntaxKind.WhenKeyword:
case SyntaxKind.UnderscoreToken:
case SyntaxKind.VarKeyword:
case SyntaxKind.OrKeyword:
case SyntaxKind.AndKeyword:
case SyntaxKind.NotKeyword:
case SyntaxKind.WithKeyword:
case SyntaxKind.InitKeyword:
case SyntaxKind.RecordKeyword:
case SyntaxKind.ManagedKeyword:
case SyntaxKind.UnmanagedKeyword:
return true;
default:
return false;
}
}
public static bool IsQueryContextualKeyword(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.FromKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.SelectKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.IntoKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.ByKeyword:
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return true;
default:
return false;
}
}
public static SyntaxKind GetContextualKeywordKind(string text)
{
switch (text)
{
case "yield":
return SyntaxKind.YieldKeyword;
case "partial":
return SyntaxKind.PartialKeyword;
case "from":
return SyntaxKind.FromKeyword;
case "group":
return SyntaxKind.GroupKeyword;
case "join":
return SyntaxKind.JoinKeyword;
case "into":
return SyntaxKind.IntoKeyword;
case "let":
return SyntaxKind.LetKeyword;
case "by":
return SyntaxKind.ByKeyword;
case "where":
return SyntaxKind.WhereKeyword;
case "select":
return SyntaxKind.SelectKeyword;
case "get":
return SyntaxKind.GetKeyword;
case "set":
return SyntaxKind.SetKeyword;
case "add":
return SyntaxKind.AddKeyword;
case "remove":
return SyntaxKind.RemoveKeyword;
case "orderby":
return SyntaxKind.OrderByKeyword;
case "alias":
return SyntaxKind.AliasKeyword;
case "on":
return SyntaxKind.OnKeyword;
case "equals":
return SyntaxKind.EqualsKeyword;
case "ascending":
return SyntaxKind.AscendingKeyword;
case "descending":
return SyntaxKind.DescendingKeyword;
case "assembly":
return SyntaxKind.AssemblyKeyword;
case "module":
return SyntaxKind.ModuleKeyword;
case "type":
return SyntaxKind.TypeKeyword;
case "field":
return SyntaxKind.FieldKeyword;
case "method":
return SyntaxKind.MethodKeyword;
case "param":
return SyntaxKind.ParamKeyword;
case "property":
return SyntaxKind.PropertyKeyword;
case "typevar":
return SyntaxKind.TypeVarKeyword;
case "global":
return SyntaxKind.GlobalKeyword;
case "async":
return SyntaxKind.AsyncKeyword;
case "await":
return SyntaxKind.AwaitKeyword;
case "when":
return SyntaxKind.WhenKeyword;
case "nameof":
return SyntaxKind.NameOfKeyword;
case "_":
return SyntaxKind.UnderscoreToken;
case "var":
return SyntaxKind.VarKeyword;
case "and":
return SyntaxKind.AndKeyword;
case "or":
return SyntaxKind.OrKeyword;
case "not":
return SyntaxKind.NotKeyword;
case "with":
return SyntaxKind.WithKeyword;
case "init":
return SyntaxKind.InitKeyword;
case "record":
return SyntaxKind.RecordKeyword;
case "managed":
return SyntaxKind.ManagedKeyword;
case "unmanaged":
return SyntaxKind.UnmanagedKeyword;
default:
return SyntaxKind.None;
}
}
public static string GetText(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TildeToken:
return "~";
case SyntaxKind.ExclamationToken:
return "!";
case SyntaxKind.DollarToken:
return "$";
case SyntaxKind.PercentToken:
return "%";
case SyntaxKind.CaretToken:
return "^";
case SyntaxKind.AmpersandToken:
return "&";
case SyntaxKind.AsteriskToken:
return "*";
case SyntaxKind.OpenParenToken:
return "(";
case SyntaxKind.CloseParenToken:
return ")";
case SyntaxKind.MinusToken:
return "-";
case SyntaxKind.PlusToken:
return "+";
case SyntaxKind.EqualsToken:
return "=";
case SyntaxKind.OpenBraceToken:
return "{";
case SyntaxKind.CloseBraceToken:
return "}";
case SyntaxKind.OpenBracketToken:
return "[";
case SyntaxKind.CloseBracketToken:
return "]";
case SyntaxKind.BarToken:
return "|";
case SyntaxKind.BackslashToken:
return "\\";
case SyntaxKind.ColonToken:
return ":";
case SyntaxKind.SemicolonToken:
return ";";
case SyntaxKind.DoubleQuoteToken:
return "\"";
case SyntaxKind.SingleQuoteToken:
return "'";
case SyntaxKind.LessThanToken:
return "<";
case SyntaxKind.CommaToken:
return ",";
case SyntaxKind.GreaterThanToken:
return ">";
case SyntaxKind.DotToken:
return ".";
case SyntaxKind.QuestionToken:
return "?";
case SyntaxKind.HashToken:
return "#";
case SyntaxKind.SlashToken:
return "/";
case SyntaxKind.SlashGreaterThanToken:
return "/>";
case SyntaxKind.LessThanSlashToken:
return "</";
case SyntaxKind.XmlCommentStartToken:
return "<!--";
case SyntaxKind.XmlCommentEndToken:
return "-->";
case SyntaxKind.XmlCDataStartToken:
return "<![CDATA[";
case SyntaxKind.XmlCDataEndToken:
return "]]>";
case SyntaxKind.XmlProcessingInstructionStartToken:
return "<?";
case SyntaxKind.XmlProcessingInstructionEndToken:
return "?>";
// compound
case SyntaxKind.BarBarToken:
return "||";
case SyntaxKind.AmpersandAmpersandToken:
return "&&";
case SyntaxKind.MinusMinusToken:
return "--";
case SyntaxKind.PlusPlusToken:
return "++";
case SyntaxKind.ColonColonToken:
return "::";
case SyntaxKind.QuestionQuestionToken:
return "??";
case SyntaxKind.MinusGreaterThanToken:
return "->";
case SyntaxKind.ExclamationEqualsToken:
return "!=";
case SyntaxKind.EqualsEqualsToken:
return "==";
case SyntaxKind.EqualsGreaterThanToken:
return "=>";
case SyntaxKind.LessThanEqualsToken:
return "<=";
case SyntaxKind.LessThanLessThanToken:
return "<<";
case SyntaxKind.LessThanLessThanEqualsToken:
return "<<=";
case SyntaxKind.GreaterThanEqualsToken:
return ">=";
case SyntaxKind.GreaterThanGreaterThanToken:
return ">>";
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return ">>=";
case SyntaxKind.SlashEqualsToken:
return "/=";
case SyntaxKind.AsteriskEqualsToken:
return "*=";
case SyntaxKind.BarEqualsToken:
return "|=";
case SyntaxKind.AmpersandEqualsToken:
return "&=";
case SyntaxKind.PlusEqualsToken:
return "+=";
case SyntaxKind.MinusEqualsToken:
return "-=";
case SyntaxKind.CaretEqualsToken:
return "^=";
case SyntaxKind.PercentEqualsToken:
return "%=";
case SyntaxKind.QuestionQuestionEqualsToken:
return "??=";
case SyntaxKind.DotDotToken:
return "..";
// Keywords
case SyntaxKind.BoolKeyword:
return "bool";
case SyntaxKind.ByteKeyword:
return "byte";
case SyntaxKind.SByteKeyword:
return "sbyte";
case SyntaxKind.ShortKeyword:
return "short";
case SyntaxKind.UShortKeyword:
return "ushort";
case SyntaxKind.IntKeyword:
return "int";
case SyntaxKind.UIntKeyword:
return "uint";
case SyntaxKind.LongKeyword:
return "long";
case SyntaxKind.ULongKeyword:
return "ulong";
case SyntaxKind.DoubleKeyword:
return "double";
case SyntaxKind.FloatKeyword:
return "float";
case SyntaxKind.DecimalKeyword:
return "decimal";
case SyntaxKind.StringKeyword:
return "string";
case SyntaxKind.CharKeyword:
return "char";
case SyntaxKind.VoidKeyword:
return "void";
case SyntaxKind.ObjectKeyword:
return "object";
case SyntaxKind.TypeOfKeyword:
return "typeof";
case SyntaxKind.SizeOfKeyword:
return "sizeof";
case SyntaxKind.NullKeyword:
return "null";
case SyntaxKind.TrueKeyword:
return "true";
case SyntaxKind.FalseKeyword:
return "false";
case SyntaxKind.IfKeyword:
return "if";
case SyntaxKind.ElseKeyword:
return "else";
case SyntaxKind.WhileKeyword:
return "while";
case SyntaxKind.ForKeyword:
return "for";
case SyntaxKind.ForEachKeyword:
return "foreach";
case SyntaxKind.DoKeyword:
return "do";
case SyntaxKind.SwitchKeyword:
return "switch";
case SyntaxKind.CaseKeyword:
return "case";
case SyntaxKind.DefaultKeyword:
return "default";
case SyntaxKind.TryKeyword:
return "try";
case SyntaxKind.CatchKeyword:
return "catch";
case SyntaxKind.FinallyKeyword:
return "finally";
case SyntaxKind.LockKeyword:
return "lock";
case SyntaxKind.GotoKeyword:
return "goto";
case SyntaxKind.BreakKeyword:
return "break";
case SyntaxKind.ContinueKeyword:
return "continue";
case SyntaxKind.ReturnKeyword:
return "return";
case SyntaxKind.ThrowKeyword:
return "throw";
case SyntaxKind.PublicKeyword:
return "public";
case SyntaxKind.PrivateKeyword:
return "private";
case SyntaxKind.InternalKeyword:
return "internal";
case SyntaxKind.ProtectedKeyword:
return "protected";
case SyntaxKind.StaticKeyword:
return "static";
case SyntaxKind.ReadOnlyKeyword:
return "readonly";
case SyntaxKind.SealedKeyword:
return "sealed";
case SyntaxKind.ConstKeyword:
return "const";
case SyntaxKind.FixedKeyword:
return "fixed";
case SyntaxKind.StackAllocKeyword:
return "stackalloc";
case SyntaxKind.VolatileKeyword:
return "volatile";
case SyntaxKind.NewKeyword:
return "new";
case SyntaxKind.OverrideKeyword:
return "override";
case SyntaxKind.AbstractKeyword:
return "abstract";
case SyntaxKind.VirtualKeyword:
return "virtual";
case SyntaxKind.EventKeyword:
return "event";
case SyntaxKind.ExternKeyword:
return "extern";
case SyntaxKind.RefKeyword:
return "ref";
case SyntaxKind.OutKeyword:
return "out";
case SyntaxKind.InKeyword:
return "in";
case SyntaxKind.IsKeyword:
return "is";
case SyntaxKind.AsKeyword:
return "as";
case SyntaxKind.ParamsKeyword:
return "params";
case SyntaxKind.ArgListKeyword:
return "__arglist";
case SyntaxKind.MakeRefKeyword:
return "__makeref";
case SyntaxKind.RefTypeKeyword:
return "__reftype";
case SyntaxKind.RefValueKeyword:
return "__refvalue";
case SyntaxKind.ThisKeyword:
return "this";
case SyntaxKind.BaseKeyword:
return "base";
case SyntaxKind.NamespaceKeyword:
return "namespace";
case SyntaxKind.UsingKeyword:
return "using";
case SyntaxKind.ClassKeyword:
return "class";
case SyntaxKind.StructKeyword:
return "struct";
case SyntaxKind.InterfaceKeyword:
return "interface";
case SyntaxKind.EnumKeyword:
return "enum";
case SyntaxKind.DelegateKeyword:
return "delegate";
case SyntaxKind.CheckedKeyword:
return "checked";
case SyntaxKind.UncheckedKeyword:
return "unchecked";
case SyntaxKind.UnsafeKeyword:
return "unsafe";
case SyntaxKind.OperatorKeyword:
return "operator";
case SyntaxKind.ImplicitKeyword:
return "implicit";
case SyntaxKind.ExplicitKeyword:
return "explicit";
case SyntaxKind.ElifKeyword:
return "elif";
case SyntaxKind.EndIfKeyword:
return "endif";
case SyntaxKind.RegionKeyword:
return "region";
case SyntaxKind.EndRegionKeyword:
return "endregion";
case SyntaxKind.DefineKeyword:
return "define";
case SyntaxKind.UndefKeyword:
return "undef";
case SyntaxKind.WarningKeyword:
return "warning";
case SyntaxKind.ErrorKeyword:
return "error";
case SyntaxKind.LineKeyword:
return "line";
case SyntaxKind.PragmaKeyword:
return "pragma";
case SyntaxKind.HiddenKeyword:
return "hidden";
case SyntaxKind.ChecksumKeyword:
return "checksum";
case SyntaxKind.DisableKeyword:
return "disable";
case SyntaxKind.RestoreKeyword:
return "restore";
case SyntaxKind.ReferenceKeyword:
return "r";
case SyntaxKind.LoadKeyword:
return "load";
case SyntaxKind.NullableKeyword:
return "nullable";
case SyntaxKind.EnableKeyword:
return "enable";
case SyntaxKind.WarningsKeyword:
return "warnings";
case SyntaxKind.AnnotationsKeyword:
return "annotations";
// contextual keywords
case SyntaxKind.YieldKeyword:
return "yield";
case SyntaxKind.PartialKeyword:
return "partial";
case SyntaxKind.FromKeyword:
return "from";
case SyntaxKind.GroupKeyword:
return "group";
case SyntaxKind.JoinKeyword:
return "join";
case SyntaxKind.IntoKeyword:
return "into";
case SyntaxKind.LetKeyword:
return "let";
case SyntaxKind.ByKeyword:
return "by";
case SyntaxKind.WhereKeyword:
return "where";
case SyntaxKind.SelectKeyword:
return "select";
case SyntaxKind.GetKeyword:
return "get";
case SyntaxKind.SetKeyword:
return "set";
case SyntaxKind.AddKeyword:
return "add";
case SyntaxKind.RemoveKeyword:
return "remove";
case SyntaxKind.OrderByKeyword:
return "orderby";
case SyntaxKind.AliasKeyword:
return "alias";
case SyntaxKind.OnKeyword:
return "on";
case SyntaxKind.EqualsKeyword:
return "equals";
case SyntaxKind.AscendingKeyword:
return "ascending";
case SyntaxKind.DescendingKeyword:
return "descending";
case SyntaxKind.AssemblyKeyword:
return "assembly";
case SyntaxKind.ModuleKeyword:
return "module";
case SyntaxKind.TypeKeyword:
return "type";
case SyntaxKind.FieldKeyword:
return "field";
case SyntaxKind.MethodKeyword:
return "method";
case SyntaxKind.ParamKeyword:
return "param";
case SyntaxKind.PropertyKeyword:
return "property";
case SyntaxKind.TypeVarKeyword:
return "typevar";
case SyntaxKind.GlobalKeyword:
return "global";
case SyntaxKind.NameOfKeyword:
return "nameof";
case SyntaxKind.AsyncKeyword:
return "async";
case SyntaxKind.AwaitKeyword:
return "await";
case SyntaxKind.WhenKeyword:
return "when";
case SyntaxKind.InterpolatedStringStartToken:
return "$\"";
case SyntaxKind.InterpolatedStringEndToken:
return "\"";
case SyntaxKind.InterpolatedVerbatimStringStartToken:
return "$@\"";
case SyntaxKind.UnderscoreToken:
return "_";
case SyntaxKind.VarKeyword:
return "var";
case SyntaxKind.AndKeyword:
return "and";
case SyntaxKind.OrKeyword:
return "or";
case SyntaxKind.NotKeyword:
return "not";
case SyntaxKind.WithKeyword:
return "with";
case SyntaxKind.InitKeyword:
return "init";
case SyntaxKind.RecordKeyword:
return "record";
case SyntaxKind.ManagedKeyword:
return "managed";
case SyntaxKind.UnmanagedKeyword:
return "unmanaged";
default:
return string.Empty;
}
}
public static bool IsTypeParameterVarianceKeyword(SyntaxKind kind)
{
return kind == SyntaxKind.OutKeyword || kind == SyntaxKind.InKeyword;
}
public static bool IsDocumentationCommentTrivia(SyntaxKind kind)
{
return kind == SyntaxKind.SingleLineDocumentationCommentTrivia ||
kind == SyntaxKind.MultiLineDocumentationCommentTrivia;
}
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Helpers/TestTypeExtensions.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.CompilerServices
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Friend Module TestTypeExtensions
<Extension>
Public Function GetTypeName(type As System.Type, Optional typeInfo As DkmClrCustomTypeInfo = Nothing, Optional escapeKeywordIdentifiers As Boolean = False, Optional inspectionContext As DkmInspectionContext = Nothing) As String
Dim formatter = New VisualBasicFormatter()
Dim clrType = New DkmClrType(New TypeImpl(type))
If inspectionContext Is Nothing Then
Dim inspectionSession = New DkmInspectionSession(ImmutableArray.Create(Of IDkmClrFormatter)(New VisualBasicFormatter()), ImmutableArray.Create(Of IDkmClrResultProvider)(New VisualBasicResultProvider()))
inspectionContext = New DkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix:=10, runtimeInstance:=Nothing)
End If
Return If(escapeKeywordIdentifiers,
DirectCast(formatter, IDkmClrFullNameProvider).GetClrTypeName(inspectionContext, clrType, typeInfo),
DirectCast(formatter, IDkmClrFormatter).GetTypeName(inspectionContext, clrType, typeInfo, Microsoft.CodeAnalysis.ExpressionEvaluator.Formatter.NoFormatSpecifiers))
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces
Imports Microsoft.VisualStudio.Debugger.Evaluation
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests
Friend Module TestTypeExtensions
<Extension>
Public Function GetTypeName(type As System.Type, Optional typeInfo As DkmClrCustomTypeInfo = Nothing, Optional escapeKeywordIdentifiers As Boolean = False, Optional inspectionContext As DkmInspectionContext = Nothing) As String
Dim formatter = New VisualBasicFormatter()
Dim clrType = New DkmClrType(New TypeImpl(type))
If inspectionContext Is Nothing Then
Dim inspectionSession = New DkmInspectionSession(ImmutableArray.Create(Of IDkmClrFormatter)(New VisualBasicFormatter()), ImmutableArray.Create(Of IDkmClrResultProvider)(New VisualBasicResultProvider()))
inspectionContext = New DkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix:=10, runtimeInstance:=Nothing)
End If
Return If(escapeKeywordIdentifiers,
DirectCast(formatter, IDkmClrFullNameProvider).GetClrTypeName(inspectionContext, clrType, typeInfo),
DirectCast(formatter, IDkmClrFormatter).GetTypeName(inspectionContext, clrType, typeInfo, Microsoft.CodeAnalysis.ExpressionEvaluator.Formatter.NoFormatSpecifiers))
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Features/Core/Portable/Completion/ExportCompletionProviderAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// Use this attribute to export a <see cref="CompletionProvider"/> so that it will
/// be found and used by the per language associated <see cref="CompletionService"/>.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExportCompletionProviderAttribute : ExportAttribute
{
public string Name { get; }
public string Language { get; }
public string[] Roles { get; set; }
public ExportCompletionProviderAttribute(string name, string language)
: base(typeof(CompletionProvider))
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// Use this attribute to export a <see cref="CompletionProvider"/> so that it will
/// be found and used by the per language associated <see cref="CompletionService"/>.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExportCompletionProviderAttribute : ExportAttribute
{
public string Name { get; }
public string Language { get; }
public string[] Roles { get; set; }
public ExportCompletionProviderAttribute(string name, string language)
: base(typeof(CompletionProvider))
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./src/Compilers/VisualBasic/Portable/Binding/DescendantBinderFactory.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Provides a way to obtain binders for descendant scopes in method or lambda body.
''' Factory for a method body does not create binders for scopes inside a lambda,
''' contained by the method. A dedicated factory must be created for each lambda body.
''' </summary>
Friend Class DescendantBinderFactory
Private ReadOnly _rootBinder As ExecutableCodeBinder
Private ReadOnly _root As SyntaxNode
Public Sub New(binder As ExecutableCodeBinder, root As SyntaxNode)
_rootBinder = binder
_root = root
End Sub
Friend ReadOnly Property Root As SyntaxNode
Get
Return _root
End Get
End Property
Friend ReadOnly Property RootBinder As ExecutableCodeBinder
Get
Return _rootBinder
End Get
End Property
Friend Function GetBinder(node As SyntaxNode) As Binder
Dim binder As BlockBaseBinder = Nothing
If NodeToBinderMap.TryGetValue(node, binder) Then
Return binder
Else
Return Nothing
End If
End Function
Friend Function GetBinder(statementList As SyntaxList(Of StatementSyntax)) As Binder
Dim binder As BlockBaseBinder = Nothing
If StmtListToBinderMap.TryGetValue(statementList, binder) Then
Return binder
Else
Return Nothing
End If
End Function
Private _lazyNodeToBinderMap As ImmutableDictionary(Of SyntaxNode, BlockBaseBinder)
' Get the map that maps from syntax nodes to binders.
Friend ReadOnly Property NodeToBinderMap As ImmutableDictionary(Of SyntaxNode, BlockBaseBinder)
Get
If _lazyNodeToBinderMap Is Nothing Then
BuildBinderMaps()
End If
Return _lazyNodeToBinderMap
End Get
End Property
Private _lazyStmtListToBinderMap As ImmutableDictionary(Of SyntaxList(Of StatementSyntax), BlockBaseBinder)
' Get the map that maps from statement lists to binders.
Friend ReadOnly Property StmtListToBinderMap As ImmutableDictionary(Of SyntaxList(Of StatementSyntax), BlockBaseBinder)
Get
If _lazyStmtListToBinderMap Is Nothing Then
BuildBinderMaps()
End If
Return _lazyStmtListToBinderMap
End Get
End Property
' Build the two maps that map to nodes and statement lists to binders.
Private Sub BuildBinderMaps()
Dim builder As New LocalBinderBuilder(DirectCast(_rootBinder.ContainingMember, MethodSymbol))
builder.MakeBinder(Root, RootBinder)
Interlocked.CompareExchange(_lazyNodeToBinderMap, builder.NodeToBinderMap, Nothing)
Interlocked.CompareExchange(_lazyStmtListToBinderMap, builder.StmtListToBinderMap, Nothing)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Provides a way to obtain binders for descendant scopes in method or lambda body.
''' Factory for a method body does not create binders for scopes inside a lambda,
''' contained by the method. A dedicated factory must be created for each lambda body.
''' </summary>
Friend Class DescendantBinderFactory
Private ReadOnly _rootBinder As ExecutableCodeBinder
Private ReadOnly _root As SyntaxNode
Public Sub New(binder As ExecutableCodeBinder, root As SyntaxNode)
_rootBinder = binder
_root = root
End Sub
Friend ReadOnly Property Root As SyntaxNode
Get
Return _root
End Get
End Property
Friend ReadOnly Property RootBinder As ExecutableCodeBinder
Get
Return _rootBinder
End Get
End Property
Friend Function GetBinder(node As SyntaxNode) As Binder
Dim binder As BlockBaseBinder = Nothing
If NodeToBinderMap.TryGetValue(node, binder) Then
Return binder
Else
Return Nothing
End If
End Function
Friend Function GetBinder(statementList As SyntaxList(Of StatementSyntax)) As Binder
Dim binder As BlockBaseBinder = Nothing
If StmtListToBinderMap.TryGetValue(statementList, binder) Then
Return binder
Else
Return Nothing
End If
End Function
Private _lazyNodeToBinderMap As ImmutableDictionary(Of SyntaxNode, BlockBaseBinder)
' Get the map that maps from syntax nodes to binders.
Friend ReadOnly Property NodeToBinderMap As ImmutableDictionary(Of SyntaxNode, BlockBaseBinder)
Get
If _lazyNodeToBinderMap Is Nothing Then
BuildBinderMaps()
End If
Return _lazyNodeToBinderMap
End Get
End Property
Private _lazyStmtListToBinderMap As ImmutableDictionary(Of SyntaxList(Of StatementSyntax), BlockBaseBinder)
' Get the map that maps from statement lists to binders.
Friend ReadOnly Property StmtListToBinderMap As ImmutableDictionary(Of SyntaxList(Of StatementSyntax), BlockBaseBinder)
Get
If _lazyStmtListToBinderMap Is Nothing Then
BuildBinderMaps()
End If
Return _lazyStmtListToBinderMap
End Get
End Property
' Build the two maps that map to nodes and statement lists to binders.
Private Sub BuildBinderMaps()
Dim builder As New LocalBinderBuilder(DirectCast(_rootBinder.ContainingMember, MethodSymbol))
builder.MakeBinder(Root, RootBinder)
Interlocked.CompareExchange(_lazyNodeToBinderMap, builder.NodeToBinderMap, Nothing)
Interlocked.CompareExchange(_lazyStmtListToBinderMap, builder.StmtListToBinderMap, Nothing)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,023 | Add generator driver cache to VBCSCompiler | - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | chsienki | 2021-07-21T20:04:49Z | 2021-08-31T17:58:33Z | 94d1ae57cafdc55d3c4726bd5bad21eed0a73b2e | e01c311bd91e6290eefe9be9eeef76c64b08b2d5 | Add generator driver cache to VBCSCompiler. - Create a new cache type
- Make the compiler optionally take it
- Pass in the cache when running on the server
- Check the cache (if there is one) for a generator driver before creating a new one
This enables incrementalism in the compiler server so that subsequent command line builds will be faster when using incremental generators. | ./docs/compilers/Design/Unexpected Conditions.md | These are [guidelines](https://www.youtube.com/watch?v=6GMkuPiIZ2k) for writing code that may encounter "impossible" and unexpected program conditions. Like other *coding guidelines*, there is value in being somewhat uniform across the code base even though we may have opinions that differ. When you have a good reason to vary from these guidelines, please add comments that explain the variance for those who come after you.
- Use `Debug.Assert(Condition)` to document invariants in the code. Although these dissolve away into nothing in non-Debug builds, as an open-source project we have little control over whether our customers are running our code with Debug enabled. Therefore such assertions should not consume excessive execution time. We may consider having such assertions run in production builds in the future. If we find they are too expensive we may create work items to improve their performance.
- If you write a switch statement that is intended to be exhaustive of the possibilities, add a default branch with `throw ExceptionUtilities.UnexpectedValue(switchExpression);`.
- Similarly, if you have a sequence of `if-then-else if` statements that is intended to be exhaustive of the possibilities, add a final "impossible" else branch with `throw ExceptionUtilities.Unreachable;` or, if is convenient to provide interesting, easy to obtain data for the diagnostic, use `ExceptionUtilities.UnexpectedValue`. Do this also for other situations where the code reaches a point that is "impossible".
- Validation of preconditions in public APIs should be done with plain code. Report a diagnostic if one exists for the situation (e.g. a syntax error), or throw an appropriate exception such as `ArgumentNullException` or `ArgumentException`.
- If you run into some other weird error case that would be fatal, throw `InvalidOperationException` with interesting, straightforward to get, data in the message. These should be rare and should be accompanied by a comment explaining why an `Assert` is not sufficient.
By following these guidelines, you should find no reason to write `Debug.Assert(false)`. If you find that in your code consider if one of these bullets suggests a different way to handle the situation.
| These are [guidelines](https://www.youtube.com/watch?v=6GMkuPiIZ2k) for writing code that may encounter "impossible" and unexpected program conditions. Like other *coding guidelines*, there is value in being somewhat uniform across the code base even though we may have opinions that differ. When you have a good reason to vary from these guidelines, please add comments that explain the variance for those who come after you.
- Use `Debug.Assert(Condition)` to document invariants in the code. Although these dissolve away into nothing in non-Debug builds, as an open-source project we have little control over whether our customers are running our code with Debug enabled. Therefore such assertions should not consume excessive execution time. We may consider having such assertions run in production builds in the future. If we find they are too expensive we may create work items to improve their performance.
- If you write a switch statement that is intended to be exhaustive of the possibilities, add a default branch with `throw ExceptionUtilities.UnexpectedValue(switchExpression);`.
- Similarly, if you have a sequence of `if-then-else if` statements that is intended to be exhaustive of the possibilities, add a final "impossible" else branch with `throw ExceptionUtilities.Unreachable;` or, if is convenient to provide interesting, easy to obtain data for the diagnostic, use `ExceptionUtilities.UnexpectedValue`. Do this also for other situations where the code reaches a point that is "impossible".
- Validation of preconditions in public APIs should be done with plain code. Report a diagnostic if one exists for the situation (e.g. a syntax error), or throw an appropriate exception such as `ArgumentNullException` or `ArgumentException`.
- If you run into some other weird error case that would be fatal, throw `InvalidOperationException` with interesting, straightforward to get, data in the message. These should be rare and should be accompanied by a comment explaining why an `Assert` is not sufficient.
By following these guidelines, you should find no reason to write `Debug.Assert(false)`. If you find that in your code consider if one of these bullets suggests a different way to handle the situation.
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Analyzers/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpMatchFolderAndNamespaceDiagnosticAnalyzer
: AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<SyntaxKind, BaseNamespaceDeclarationSyntax>
{
protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance;
protected override ImmutableArray<SyntaxKind> GetSyntaxKindsToAnalyze()
=> ImmutableArray.Create(SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpMatchFolderAndNamespaceDiagnosticAnalyzer
: AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<SyntaxKind, BaseNamespaceDeclarationSyntax>
{
protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance;
protected override ImmutableArray<SyntaxKind> GetSyntaxKindsToAnalyze()
=> ImmutableArray.Create(SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration);
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace
{
public class CSharpMatchFolderAndNamespaceTests
{
private static readonly string Directory = Path.Combine("Test", "Directory");
// DefaultNamespace gets exposed as RootNamespace in the build properties
private const string DefaultNamespace = "Test.Root.Namespace";
private static readonly string EditorConfig = @$"
is_global=true
build_property.ProjectDir = {Directory}
build_property.RootNamespace = {DefaultNamespace}
";
private static string CreateFolderPath(params string[] folders)
=> Path.Combine(Directory, Path.Combine(folders));
private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null)
{
var filePath = Path.Combine(directory ?? Directory, fileName);
fixedCode ??= fileContents;
return RunTestAsync(
new[] { (filePath, fileContents) },
new[] { (filePath, fixedCode) },
editorConfig);
}
private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null)
{
var testState = new VerifyCS.Test
{
EditorConfig = editorconfig ?? EditorConfig,
CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck,
LanguageVersion = LanguageVersion.CSharp10,
};
foreach (var (fileName, content) in originalSources)
testState.TestState.Sources.Add((fileName, content));
fixedSources ??= Array.Empty<(string, string)>();
foreach (var (fileName, content) in fixedSources)
testState.FixedState.Sources.Add((fileName, content));
return testState.RunAsync();
}
[Fact]
public Task InvalidFolderName1_NoDiagnostic()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { "3B", "C" });
var code =
@"
namespace A.B
{
class Class1
{
}
}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { "3B", "C" });
var code =
@"
namespace A.B;
class Class1
{
}
";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task InvalidFolderName2_NoDiagnostic()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { "B.3C", "D" });
var code =
@"
namespace A.B
{
class Class1
{
}
}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task InvalidFolderName3_NoDiagnostic()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" });
var code =
@"
namespace A.B
{
class Class1
{
}
}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task CaseInsensitiveMatch_NoDiagnostic()
{
var folder = CreateFolderPath(new[] { "A", "B" });
var code =
@$"
namespace {DefaultNamespace}.a.b
{{
class Class1
{{
}}
}}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public async Task SingleDocumentNoReference()
{
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|]
{
class Class1
{
}
}";
var fixedCode =
@$"namespace {DefaultNamespace}.B.C
{{
class Class1
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode);
}
[Fact]
public async Task SingleDocumentNoReference_FileScopedNamespace()
{
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|];
class Class1
{
}
";
var fixedCode =
@$"namespace {DefaultNamespace}.B.C;
class Class1
{{
}}
";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode);
}
[Fact]
public async Task SingleDocumentNoReference_NoDefaultNamespace()
{
var editorConfig = @$"
is_global=true
build_property.ProjectDir = {Directory}
";
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|]
{
class Class1
{
}
}";
var fixedCode =
@$"namespace B.C
{{
class Class1
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode,
editorConfig: editorConfig);
}
[Fact]
public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespace()
{
var editorConfig = @$"
is_global=true
build_property.ProjectDir = {Directory}
";
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|];
class Class1
{
}
";
var fixedCode =
@$"namespace B.C;
class Class1
{{
}}
";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode,
editorConfig: editorConfig);
}
[Fact]
public async Task NamespaceWithSpaces_NoDiagnostic()
{
var folder = CreateFolderPath("A", "B");
var code =
@$"namespace {DefaultNamespace}.A . B
{{
class Class1
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder);
}
[Fact]
public async Task NestedNamespaces_NoDiagnostic()
{
// The code fix doesn't currently support nested namespaces for sync, so
// diagnostic does not report.
var folder = CreateFolderPath("B", "C");
var code =
@"namespace A.B
{
namespace C.D
{
class CDClass
{
}
}
class ABClass
{
}
}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder);
}
[Fact]
public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic()
{
// The code fix doesn't currently support nested namespaces for sync, so
// diagnostic does not report.
var folder = CreateFolderPath("B", "C");
var code1 =
@"namespace A.B
{
partial class ABClass
{
void M1() {}
}
}";
var code2 =
@"namespace A.B
{
partial class ABClass
{
void M2() {}
}
}";
var sources = new[]
{
(Path.Combine(folder, "ABClass1.cs"), code1),
(Path.Combine(folder, "ABClass2.cs"), code2),
};
await RunTestAsync(sources);
}
[Fact]
public async Task FileNotInProjectFolder_NoDiagnostic()
{
// Default directory is Test\Directory for the project,
// putting the file outside the directory should have no
// diagnostic shown.
var folder = Path.Combine("B", "C");
var code =
$@"namespace A.B
{{
class ABClass
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder);
}
[Fact]
public async Task SingleDocumentLocalReference()
{
var @namespace = "Bar.Baz";
var folder = CreateFolderPath("A", "B", "C");
var code =
$@"
namespace [|{@namespace}|]
{{
delegate void D1();
interface Class1
{{
void M1();
}}
class Class2 : {@namespace}.Class1
{{
{@namespace}.D1 d;
void {@namespace}.Class1.M1(){{}}
}}
}}";
var expected =
@$"namespace {DefaultNamespace}.A.B.C
{{
delegate void D1();
interface Class1
{{
void M1();
}}
class Class2 : Class1
{{
D1 d;
void Class1.M1() {{ }}
}}
}}";
await RunTestAsync(
"Class1.cs",
code,
folder,
fixedCode: expected);
}
[Fact]
public async Task ChangeUsingsInMultipleContainers()
{
var declaredNamespace = "Bar.Baz";
var folder = CreateFolderPath("A", "B", "C");
var code1 =
$@"namespace [|{declaredNamespace}|]
{{
class Class1
{{
}}
}}";
var code2 =
$@"namespace NS1
{{
using {declaredNamespace};
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using {declaredNamespace};
class Class2
{{
Class1 c1;
}}
}}
}}";
var fixed1 =
@$"namespace {DefaultNamespace}.A.B.C
{{
class Class1
{{
}}
}}";
var fixed2 =
@$"namespace NS1
{{
using {DefaultNamespace}.A.B.C;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
class Class2
{{
Class1 c1;
}}
}}
}}";
var originalSources = new[]
{
(Path.Combine(folder, "Class1.cs"), code1),
("Class2.cs", code2)
};
var fixedSources = new[]
{
(Path.Combine(folder, "Class1.cs"), fixed1),
("Class2.cs", fixed2)
};
await RunTestAsync(originalSources, fixedSources);
}
[Fact]
public async Task ChangeNamespace_WithAliasReferencesInOtherDocument()
{
var declaredNamespace = $"Bar.Baz";
var folder = CreateFolderPath("A", "B", "C");
var code1 =
$@"namespace [|{declaredNamespace}|]
{{
class Class1
{{
}}
}}";
var code2 = $@"
using System;
using {declaredNamespace};
using Class1Alias = {declaredNamespace}.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
}}
}}";
var fixed1 =
@$"namespace {DefaultNamespace}.A.B.C
{{
class Class1
{{
}}
}}";
var fixed2 =
@$"
using System;
using Class1Alias = {DefaultNamespace}.A.B.C.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
}}
}}";
var originalSources = new[]
{
(Path.Combine(folder, "Class1.cs"), code1),
("Class2.cs", code2)
};
var fixedSources = new[]
{
(Path.Combine(folder, "Class1.cs"), fixed1),
("Class2.cs", fixed2)
};
await RunTestAsync(originalSources, fixedSources);
}
[Fact]
public async Task FixAll()
{
var declaredNamespace = "Bar.Baz";
var folder1 = CreateFolderPath("A", "B", "C");
var fixedNamespace1 = $"{DefaultNamespace}.A.B.C";
var folder2 = CreateFolderPath("Second", "Folder", "Path");
var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path";
var folder3 = CreateFolderPath("Third", "Folder", "Path");
var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path";
var code1 =
$@"namespace [|{declaredNamespace}|]
{{
class Class1
{{
Class2 C2 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var fixed1 =
$@"using {fixedNamespace2};
using {fixedNamespace3};
namespace {fixedNamespace1}
{{
class Class1
{{
Class2 C2 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var code2 =
$@"namespace [|{declaredNamespace}|]
{{
class Class2
{{
Class1 C1 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var fixed2 =
$@"using {fixedNamespace1};
using {fixedNamespace3};
namespace {fixedNamespace2}
{{
class Class2
{{
Class1 C1 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var code3 =
$@"namespace [|{declaredNamespace}|]
{{
class Class3
{{
Class1 C1 {{ get; }}
Class2 C2 {{ get; }}
}}
}}";
var fixed3 =
$@"using {fixedNamespace1};
using {fixedNamespace2};
namespace {fixedNamespace3}
{{
class Class3
{{
Class1 C1 {{ get; }}
Class2 C2 {{ get; }}
}}
}}";
var sources = new[]
{
(Path.Combine(folder1, "Class1.cs"), code1),
(Path.Combine(folder2, "Class2.cs"), code2),
(Path.Combine(folder3, "Class3.cs"), code3),
};
var fixedSources = new[]
{
(Path.Combine(folder1, "Class1.cs"), fixed1),
(Path.Combine(folder2, "Class2.cs"), fixed2),
(Path.Combine(folder3, "Class3.cs"), fixed3),
};
await RunTestAsync(sources, fixedSources);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace
{
public class CSharpMatchFolderAndNamespaceTests
{
private static readonly string Directory = Path.Combine("Test", "Directory");
// DefaultNamespace gets exposed as RootNamespace in the build properties
private const string DefaultNamespace = "Test.Root.Namespace";
private static readonly string EditorConfig = @$"
is_global=true
build_property.ProjectDir = {Directory}
build_property.RootNamespace = {DefaultNamespace}
";
private static string CreateFolderPath(params string[] folders)
=> Path.Combine(Directory, Path.Combine(folders));
private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null)
{
var filePath = Path.Combine(directory ?? Directory, fileName);
fixedCode ??= fileContents;
return RunTestAsync(
new[] { (filePath, fileContents) },
new[] { (filePath, fixedCode) },
editorConfig);
}
private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null)
{
var testState = new VerifyCS.Test
{
EditorConfig = editorconfig ?? EditorConfig,
CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck,
LanguageVersion = LanguageVersion.CSharp10,
};
foreach (var (fileName, content) in originalSources)
testState.TestState.Sources.Add((fileName, content));
fixedSources ??= Array.Empty<(string, string)>();
foreach (var (fileName, content) in fixedSources)
testState.FixedState.Sources.Add((fileName, content));
return testState.RunAsync();
}
[Fact]
public Task InvalidFolderName1_NoDiagnostic()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { "3B", "C" });
var code =
@"
namespace A.B
{
class Class1
{
}
}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { "3B", "C" });
var code =
@"
namespace A.B;
class Class1
{
}
";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task InvalidFolderName2_NoDiagnostic()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { "B.3C", "D" });
var code =
@"
namespace A.B
{
class Class1
{
}
}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task InvalidFolderName3_NoDiagnostic()
{
// No change namespace action because the folder name is not valid identifier
var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" });
var code =
@"
namespace A.B
{
class Class1
{
}
}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public Task CaseInsensitiveMatch_NoDiagnostic()
{
var folder = CreateFolderPath(new[] { "A", "B" });
var code =
@$"
namespace {DefaultNamespace}.a.b
{{
class Class1
{{
}}
}}";
return RunTestAsync(
"File1.cs",
code,
directory: folder);
}
[Fact]
public async Task SingleDocumentNoReference()
{
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|]
{
class Class1
{
}
}";
var fixedCode =
@$"namespace {DefaultNamespace}.B.C
{{
class Class1
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode);
}
[Fact]
public async Task SingleDocumentNoReference_FileScopedNamespace()
{
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|];
class Class1
{
}
";
var fixedCode =
@$"namespace {DefaultNamespace}.B.C;
class Class1
{{
}}
";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode);
}
[Fact]
public async Task SingleDocumentNoReference_NoDefaultNamespace()
{
var editorConfig = @$"
is_global=true
build_property.ProjectDir = {Directory}
";
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|]
{
class Class1
{
}
}";
var fixedCode =
@$"namespace B.C
{{
class Class1
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode,
editorConfig: editorConfig);
}
[Fact]
public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespace()
{
var editorConfig = @$"
is_global=true
build_property.ProjectDir = {Directory}
";
var folder = CreateFolderPath("B", "C");
var code =
@"namespace [|A.B|];
class Class1
{
}
";
var fixedCode =
@$"namespace B.C;
class Class1
{{
}}
";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder,
fixedCode: fixedCode,
editorConfig: editorConfig);
}
[Fact]
public async Task NamespaceWithSpaces_NoDiagnostic()
{
var folder = CreateFolderPath("A", "B");
var code =
@$"namespace {DefaultNamespace}.A . B
{{
class Class1
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder);
}
[Fact]
public async Task NestedNamespaces_NoDiagnostic()
{
// The code fix doesn't currently support nested namespaces for sync, so
// diagnostic does not report.
var folder = CreateFolderPath("B", "C");
var code =
@"namespace A.B
{
namespace C.D
{
class CDClass
{
}
}
class ABClass
{
}
}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder);
}
[Fact]
public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic()
{
// The code fix doesn't currently support nested namespaces for sync, so
// diagnostic does not report.
var folder = CreateFolderPath("B", "C");
var code1 =
@"namespace A.B
{
partial class ABClass
{
void M1() {}
}
}";
var code2 =
@"namespace A.B
{
partial class ABClass
{
void M2() {}
}
}";
var sources = new[]
{
(Path.Combine(folder, "ABClass1.cs"), code1),
(Path.Combine(folder, "ABClass2.cs"), code2),
};
await RunTestAsync(sources);
}
[Fact]
public async Task FileNotInProjectFolder_NoDiagnostic()
{
// Default directory is Test\Directory for the project,
// putting the file outside the directory should have no
// diagnostic shown.
var folder = Path.Combine("B", "C");
var code =
$@"namespace A.B
{{
class ABClass
{{
}}
}}";
await RunTestAsync(
fileName: "Class1.cs",
fileContents: code,
directory: folder);
}
[Fact]
public async Task SingleDocumentLocalReference()
{
var @namespace = "Bar.Baz";
var folder = CreateFolderPath("A", "B", "C");
var code =
$@"
namespace [|{@namespace}|]
{{
delegate void D1();
interface Class1
{{
void M1();
}}
class Class2 : {@namespace}.Class1
{{
{@namespace}.D1 d;
void {@namespace}.Class1.M1(){{}}
}}
}}";
var expected =
@$"namespace {DefaultNamespace}.A.B.C
{{
delegate void D1();
interface Class1
{{
void M1();
}}
class Class2 : Class1
{{
D1 d;
void Class1.M1() {{ }}
}}
}}";
await RunTestAsync(
"Class1.cs",
code,
folder,
fixedCode: expected);
}
[Fact]
public async Task ChangeUsingsInMultipleContainers()
{
var declaredNamespace = "Bar.Baz";
var folder = CreateFolderPath("A", "B", "C");
var code1 =
$@"namespace [|{declaredNamespace}|]
{{
class Class1
{{
}}
}}";
var code2 =
$@"namespace NS1
{{
using {declaredNamespace};
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using {declaredNamespace};
class Class2
{{
Class1 c1;
}}
}}
}}";
var fixed1 =
@$"namespace {DefaultNamespace}.A.B.C
{{
class Class1
{{
}}
}}";
var fixed2 =
@$"namespace NS1
{{
using {DefaultNamespace}.A.B.C;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
class Class2
{{
Class1 c1;
}}
}}
}}";
var originalSources = new[]
{
(Path.Combine(folder, "Class1.cs"), code1),
("Class2.cs", code2)
};
var fixedSources = new[]
{
(Path.Combine(folder, "Class1.cs"), fixed1),
("Class2.cs", fixed2)
};
await RunTestAsync(originalSources, fixedSources);
}
[Fact]
public async Task ChangeNamespace_WithAliasReferencesInOtherDocument()
{
var declaredNamespace = $"Bar.Baz";
var folder = CreateFolderPath("A", "B", "C");
var code1 =
$@"namespace [|{declaredNamespace}|]
{{
class Class1
{{
}}
}}";
var code2 = $@"
using System;
using {declaredNamespace};
using Class1Alias = {declaredNamespace}.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
}}
}}";
var fixed1 =
@$"namespace {DefaultNamespace}.A.B.C
{{
class Class1
{{
}}
}}";
var fixed2 =
@$"
using System;
using Class1Alias = {DefaultNamespace}.A.B.C.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
}}
}}";
var originalSources = new[]
{
(Path.Combine(folder, "Class1.cs"), code1),
("Class2.cs", code2)
};
var fixedSources = new[]
{
(Path.Combine(folder, "Class1.cs"), fixed1),
("Class2.cs", fixed2)
};
await RunTestAsync(originalSources, fixedSources);
}
[Fact]
public async Task FixAll()
{
var declaredNamespace = "Bar.Baz";
var folder1 = CreateFolderPath("A", "B", "C");
var fixedNamespace1 = $"{DefaultNamespace}.A.B.C";
var folder2 = CreateFolderPath("Second", "Folder", "Path");
var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path";
var folder3 = CreateFolderPath("Third", "Folder", "Path");
var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path";
var code1 =
$@"namespace [|{declaredNamespace}|]
{{
class Class1
{{
Class2 C2 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var fixed1 =
$@"using {fixedNamespace2};
using {fixedNamespace3};
namespace {fixedNamespace1}
{{
class Class1
{{
Class2 C2 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var code2 =
$@"namespace [|{declaredNamespace}|]
{{
class Class2
{{
Class1 C1 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var fixed2 =
$@"using {fixedNamespace1};
using {fixedNamespace3};
namespace {fixedNamespace2}
{{
class Class2
{{
Class1 C1 {{ get; }}
Class3 C3 {{ get; }}
}}
}}";
var code3 =
$@"namespace [|{declaredNamespace}|]
{{
class Class3
{{
Class1 C1 {{ get; }}
Class2 C2 {{ get; }}
}}
}}";
var fixed3 =
$@"using {fixedNamespace1};
using {fixedNamespace2};
namespace {fixedNamespace3}
{{
class Class3
{{
Class1 C1 {{ get; }}
Class2 C2 {{ get; }}
}}
}}";
var sources = new[]
{
(Path.Combine(folder1, "Class1.cs"), code1),
(Path.Combine(folder2, "Class2.cs"), code2),
(Path.Combine(folder3, "Class3.cs"), code3),
};
var fixedSources = new[]
{
(Path.Combine(folder1, "Class1.cs"), fixed1),
(Path.Combine(folder2, "Class2.cs"), fixed2),
(Path.Combine(folder3, "Class3.cs"), fixed3),
};
await RunTestAsync(sources, fixedSources);
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/Core/Analyzers/MatchFolderAndNamespace/AbstractMatchFolderAndNamespaceDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace
{
internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TSyntaxKind, TNamespaceSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TNamespaceSyntax : SyntaxNode
{
private static readonly LocalizableResourceString s_localizableTitle = new(
nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
private static readonly LocalizableResourceString s_localizableInsideMessage = new(
nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat
.FullyQualifiedFormat
.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer()
: base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId,
EnforceOnBuildValues.MatchFolderAndNamespace,
CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure,
s_localizableTitle,
s_localizableInsideMessage)
{
}
protected abstract ISyntaxFacts GetSyntaxFacts();
protected abstract ImmutableArray<TSyntaxKind> GetSyntaxKindsToAnalyze();
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, GetSyntaxKindsToAnalyze());
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context)
{
// It's ok to not have a rootnamespace property, but if it's there we want to use it correctly
context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace);
// Project directory is a must to correctly get the relative path and construct a namespace
if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir)
|| string.IsNullOrEmpty(projectDir))
{
return;
}
var namespaceDecl = (TNamespaceSyntax)context.Node;
var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl);
RoslynDebug.AssertNotNull(symbol);
var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat);
if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) &&
IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken))
{
var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl);
RoslynDebug.AssertNotNull(nameSyntax);
context.ReportDiagnostic(Diagnostic.Create(
Descriptor,
nameSyntax.GetLocation(),
additionalLocations: null,
properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace),
messageArgs: new[] { currentNamespace, targetNamespace }));
}
}
private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken)
{
var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken);
// It should not be nested in other namespaces
if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any())
{
return false;
}
// It should not contain a namespace
var containsNamespace = namespaceDeclaration
.DescendantNodes(n => n is TNamespaceSyntax)
.OfType<TNamespaceSyntax>().Any();
if (containsNamespace)
{
return false;
}
// The current namespace should be valid
var isCurrentNamespaceInvalid = GetSyntaxFacts()
.GetNameOfNamespaceDeclaration(namespaceDeclaration)
?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)
?? false;
if (isCurrentNamespaceInvalid)
{
return false;
}
// It should not contain partial classes with more than one instance in the semantic model. The
// fixer does not support this scenario.
var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel);
if (containsPartialType)
{
return false;
}
return true;
}
private bool IsFileAndNamespaceMismatch(
TNamespaceSyntax namespaceDeclaration,
string? rootNamespace,
string projectDir,
string currentNamespace,
[NotNullWhen(returnValue: true)] out string? targetNamespace)
{
if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath))
{
// The file does not exist within the project directory
targetNamespace = null;
return false;
}
var relativeDirectoryPath = PathUtilities.GetRelativePath(
projectDir,
PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!);
var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace);
if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase))
{
// The namespace currently matches the folder structure or is invalid, in which case we don't want
// to provide a diagnostic.
targetNamespace = null;
return false;
}
targetNamespace = expectedNamespace;
return true;
}
/// <summary>
/// Returns true if the namespace declaration contains one or more partial types with multiple declarations.
/// </summary>
protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel)
{
var syntaxFacts = GetSyntaxFacts();
var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration)
.Where(member => syntaxFacts.IsTypeDeclaration(member));
foreach (var typeDecl in typeDeclarations)
{
var symbol = semanticModel.GetDeclaredSymbol(typeDecl);
// Simplify the check by assuming no multiple partial declarations in one document
if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1)
{
return true;
}
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace
{
internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TSyntaxKind, TNamespaceSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TNamespaceSyntax : SyntaxNode
{
private static readonly LocalizableResourceString s_localizableTitle = new(
nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
private static readonly LocalizableResourceString s_localizableInsideMessage = new(
nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources));
private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat
.FullyQualifiedFormat
.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer()
: base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId,
EnforceOnBuildValues.MatchFolderAndNamespace,
CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure,
s_localizableTitle,
s_localizableInsideMessage)
{
}
protected abstract ISyntaxFacts GetSyntaxFacts();
protected abstract ImmutableArray<TSyntaxKind> GetSyntaxKindsToAnalyze();
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, GetSyntaxKindsToAnalyze());
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context)
{
// It's ok to not have a rootnamespace property, but if it's there we want to use it correctly
context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace);
// Project directory is a must to correctly get the relative path and construct a namespace
if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir)
|| string.IsNullOrEmpty(projectDir))
{
return;
}
var namespaceDecl = (TNamespaceSyntax)context.Node;
var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl);
RoslynDebug.AssertNotNull(symbol);
var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat);
if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) &&
IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken))
{
var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl);
RoslynDebug.AssertNotNull(nameSyntax);
context.ReportDiagnostic(Diagnostic.Create(
Descriptor,
nameSyntax.GetLocation(),
additionalLocations: null,
properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace),
messageArgs: new[] { currentNamespace, targetNamespace }));
}
}
private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken)
{
var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken);
// It should not be nested in other namespaces
if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any())
{
return false;
}
// It should not contain a namespace
var containsNamespace = namespaceDeclaration
.DescendantNodes(n => n is TNamespaceSyntax)
.OfType<TNamespaceSyntax>().Any();
if (containsNamespace)
{
return false;
}
// The current namespace should be valid
var isCurrentNamespaceInvalid = GetSyntaxFacts()
.GetNameOfNamespaceDeclaration(namespaceDeclaration)
?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)
?? false;
if (isCurrentNamespaceInvalid)
{
return false;
}
// It should not contain partial classes with more than one instance in the semantic model. The
// fixer does not support this scenario.
var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel);
if (containsPartialType)
{
return false;
}
return true;
}
private bool IsFileAndNamespaceMismatch(
TNamespaceSyntax namespaceDeclaration,
string? rootNamespace,
string projectDir,
string currentNamespace,
[NotNullWhen(returnValue: true)] out string? targetNamespace)
{
if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath))
{
// The file does not exist within the project directory
targetNamespace = null;
return false;
}
var relativeDirectoryPath = PathUtilities.GetRelativePath(
projectDir,
PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!);
var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace);
if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase))
{
// The namespace currently matches the folder structure or is invalid, in which case we don't want
// to provide a diagnostic.
targetNamespace = null;
return false;
}
targetNamespace = expectedNamespace;
return true;
}
/// <summary>
/// Returns true if the namespace declaration contains one or more partial types with multiple declarations.
/// </summary>
protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel)
{
var syntaxFacts = GetSyntaxFacts();
var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration)
.Where(member => syntaxFacts.IsTypeDeclaration(member));
foreach (var typeDecl in typeDeclarations)
{
var symbol = semanticModel.GetDeclaredSymbol(typeDecl);
// Simplify the check by assuming no multiple partial declarations in one document
if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1)
{
return true;
}
}
return false;
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Tasks;
using Microsoft.CodeAnalysis.Formatting;
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 TestMissing_OnMatchingFileName()
{
var code =
@"[||]class test1 { }";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMissing_Nested_OnMatchingFileName_Simple()
{
var code =
@"class outer
{
[||]class test1 { }
}";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMatchingFileName_CaseSensitive()
{
var code =
@"[||]class Test1 { }";
await TestActionCountAsync(code, count: 2);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans1()
{
var code =
@"[|clas|]s Class1 { }
class Class2 { }";
await TestActionCountAsync(code, count: 3);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans2()
{
var code =
@"[||]class Class1 { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(14008, "https://github.com/dotnet/roslyn/issues/14008")]
public async Task TestMoveToNewFileWithFolders()
{
var code =
@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document Folders=""A\B"">
[||]class Class1 { }
class Class2 { }
</Document>
</Project>
</Workspace>";
var codeAfterMove = @"class Class2 { }
";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName,
destinationDocumentText, destinationDocumentContainers: ImmutableArray.Create("A", "B"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans3()
{
var code =
@"[|class Class1|] { }
class Class2 { }";
await TestActionCountAsync(code, count: 3);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans4()
{
var code =
@"class Class1[||] { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithNoContainerNamespace()
{
var code =
@"[||]class Class1 { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithUsingsAndNoContainerNamespace()
{
var code =
@"// Banner Text
using System;
[||]class Class1 { }
class Class2 { }";
var codeAfterMove =
@"// Banner Text
using System;
class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"// Banner Text
class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithMembers()
{
var code =
@"// Banner Text
using System;
[||]class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
class Class2 { }";
var codeAfterMove =
@"// Banner Text
class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"// Banner Text
using System;
class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithMembers2()
{
var code =
@"// Banner Text
using System;
[||]class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
class Class2
{
void Print(int x)
{
Console.WriteLine(x);
}
}";
var codeAfterMove =
@"// Banner Text
using System;
class Class2
{
void Print(int x)
{
Console.WriteLine(x);
}
}";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"// Banner Text
using System;
class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveAnInterface()
{
var code =
@"[||]interface IMoveType { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "IMoveType.cs";
var destinationDocumentText = @"interface IMoveType { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveAStruct()
{
var code =
@"[||]struct MyStruct { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "MyStruct.cs";
var destinationDocumentText = @"struct MyStruct { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveAnEnum()
{
var code =
@"[||]enum MyEnum { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "MyEnum.cs";
var destinationDocumentText = @"enum MyEnum { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithContainerNamespace()
{
var code =
@"namespace N1
{
[||]class Class1 { }
class Class2 { }
}";
var codeAfterMove =
@"namespace N1
{
class Class2 { }
}";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"namespace N1
{
class Class1 { }
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithFileScopedNamespace()
{
var code =
@"namespace N1;
[||]class Class1 { }
class Class2 { }
";
var codeAfterMove =
@"namespace N1;
class Class2 { }
";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"namespace N1;
class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_Simple()
{
var code =
@"namespace N1
{
class Class1
{
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypePreserveModifiers()
{
var code =
@"namespace N1
{
abstract class Class1
{
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
abstract partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
abstract partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(14004, "https://github.com/dotnet/roslyn/issues/14004")]
public async Task MoveNestedTypeToNewFile_Attributes1()
{
var code =
@"namespace N1
{
[Outer]
class Class1
{
[Inner]
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
[Outer]
partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
[Inner]
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")]
public async Task MoveNestedTypeToNewFile_Comments1()
{
var code =
@"namespace N1
{
/// Outer doc comment.
class Class1
{
/// Inner doc comment
[||]class Class2
{
}
}
}";
var codeAfterMove =
@"namespace N1
{
/// Outer doc comment.
partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
/// Inner doc comment
class Class2
{
}
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_Simple_DottedName()
{
var code =
@"namespace N1
{
class Class1
{
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
}
}";
var expectedDocumentName = "Class1.Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers()
{
var code =
@"namespace N1
{
class Class1
{
private int _field1;
[||]class Class2 { }
public void Method1() { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
private int _field1;
public void Method1() { }
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers()
{
var code =
@"namespace N1
{
class Class1
{
private int _field1;
[||]class Class2 { }
public void Method1() { }
}
internal class Class3
{
private void Method1() { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
private int _field1;
public void Method1() { }
}
internal class Class3
{
private void Method1() { }
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_HasMembers()
{
var code =
@"namespace N1
{
class Class1
{
private int _field1;
[||]class Class2
{
private string _field1;
public void InnerMethod() { }
}
public void Method1() { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
private int _field1;
public void Method1() { }
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2
{
private string _field1;
public void InnerMethod() { }
}
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(13969, "https://github.com/dotnet/roslyn/issues/13969")]
public async Task MoveTypeInFileWithComplexHierarchy()
{
var code =
@"namespace OuterN1.N1
{
namespace InnerN2.N2
{
class OuterClass1
{
class InnerClass2
{
}
}
}
namespace InnerN3.N3
{
class OuterClass2
{
[||]class InnerClass2
{
class InnerClass3
{
}
}
class InnerClass4
{
}
}
class OuterClass3
{
}
}
}
namespace OuterN2.N2
{
namespace InnerN3.N3
{
class OuterClass5 {
class InnerClass6 {
}
}
}
}
";
var codeAfterMove =
@"namespace OuterN1.N1
{
namespace InnerN2.N2
{
class OuterClass1
{
class InnerClass2
{
}
}
}
namespace InnerN3.N3
{
partial class OuterClass2
{
class InnerClass4
{
}
}
class OuterClass3
{
}
}
}
namespace OuterN2.N2
{
namespace InnerN3.N3
{
class OuterClass5 {
class InnerClass6 {
}
}
}
}
";
var expectedDocumentName = "InnerClass2.cs";
var destinationDocumentText =
@"namespace OuterN1.N1
{
namespace InnerN3.N3
{
partial class OuterClass2
{
class InnerClass2
{
class InnerClass3
{
}
}
}
}
}
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeUsings1()
{
var code =
@"
// Only used by inner type.
using System;
// Unused by both types.
using System.Collections;
class Outer {
[||]class Inner {
DateTime d;
}
}";
var codeAfterMove = @"
// Only used by inner type.
// Unused by both types.
using System.Collections;
partial class Outer {
}";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"
// Only used by inner type.
using System;
// Unused by both types.
partial class Outer {
class Inner {
DateTime d;
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(16283, "https://github.com/dotnet/roslyn/issues/16283")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingTrivia1()
{
var code =
@"
class Outer
{
class Inner1
{
}
[||]class Inner2
{
}
}";
var codeAfterMove = @"
partial class Outer
{
class Inner1
{
}
}";
var expectedDocumentName = "Inner2.cs";
var destinationDocumentText = @"
partial class Outer
{
class Inner2
{
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestInsertFinalNewLine()
{
var code =
@"
class Outer
{
class Inner1
{
}
[||]class Inner2
{
}
}";
var codeAfterMove = @"
partial class Outer
{
class Inner1
{
}
}";
var expectedDocumentName = "Inner2.cs";
var destinationDocumentText = @"
partial class Outer
{
class Inner2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText,
onAfterWorkspaceCreated: w =>
{
w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true)));
});
}
[WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestInsertFinalNewLine2()
{
var code =
@"
class Outer
{
class Inner1
{
}
[||]class Inner2
{
}
}";
var codeAfterMove = @"
partial class Outer
{
class Inner1
{
}
}";
var expectedDocumentName = "Inner2.cs";
var destinationDocumentText = @"
partial class Outer
{
class Inner2
{
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText,
onAfterWorkspaceCreated: w =>
{
w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false)));
});
}
[WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeRemoveOuterInheritanceTypes()
{
var code =
@"
class Outer : IComparable {
[||]class Inner : IWhatever {
DateTime d;
}
}";
var codeAfterMove =
@"
partial class Outer : IComparable {
}";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"
partial class Outer
{
class Inner : IWhatever {
DateTime d;
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithDirectives1()
{
var code =
@"using System;
namespace N
{
class Program
{
static void Main()
{
}
}
}
#if true
public class [||]Inner
{
}
#endif";
var codeAfterMove =
@"using System;
namespace N
{
class Program
{
static void Main()
{
}
}
}
#if true
#endif";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"
#if true
public class Inner
{
}
#endif";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithDirectives2()
{
var code =
@"using System;
namespace N
{
class Program
{
static void Main()
{
}
#if true
public class [||]Inner
{
}
#endif
}
}";
var codeAfterMove =
@"using System;
namespace N
{
partial class Program
{
static void Main()
{
}
#if true
#endif
}
}";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"namespace N
{
partial class Program
{
#if true
public class Inner
{
}
#endif
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingBlankLines1()
{
var code =
@"// Banner Text
using System;
[||]class Class1
{
void Foo()
{
Console.WriteLine();
}
}
class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
var codeAfterMove = @"// Banner Text
using System;
class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"// Banner Text
using System;
class Class1
{
void Foo()
{
Console.WriteLine();
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingBlankLines2()
{
var code =
@"// Banner Text
using System;
class Class1
{
void Foo()
{
Console.WriteLine();
}
}
[||]class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
var codeAfterMove = @"// Banner Text
using System;
class Class1
{
void Foo()
{
Console.WriteLine();
}
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
using System;
class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingCommentInContainer()
{
var code =
@"// Banner Text
using System;
class Class1
// Leading comment
{
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
// Leading comment
{
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingCommentInContainer2()
{
var code =
@"// Banner Text
using System;
class Class1
{ // Leading comment
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
{ // Leading comment
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestTrailingCommentInContainer()
{
var code =
@"// Banner Text
using System;
class Class1
{
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
// End of class document
}
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
{
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
// End of class document
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestTrailingCommentInContainer2()
{
var code =
@"// Banner Text
using System;
class Class1
{
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
} // End of class document
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
{
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
} // End of class document
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(50329, "https://github.com/dotnet/roslyn/issues/50329")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveRecordToNewFilePreserveUsings()
{
var code =
@"using System;
[||]record CacheContext(String Message);
class Program { }";
var codeAfterMove = @"class Program { }";
var expectedDocumentName = "CacheContext.cs";
var destinationDocumentText = @"using System;
record CacheContext(String Message);
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveClassInTopLevelStatements()
{
var code = @"
using ConsoleApp1;
using System;
var c = new C();
Console.WriteLine(c.Hello);
class [||]C
{
public string Hello => ""Hello"";
}";
var codeAfterMove = @"
using ConsoleApp1;
using System;
var c = new C();
Console.WriteLine(c.Hello);
";
var expectedDocumentName = "C.cs";
var destinationDocumentText = @"class C
{
public string Hello => ""Hello"";
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MissingInTopLevelStatementsOnly()
{
var code = @"
using ConsoleApp1;
using System;
var c = new object();
[||]Console.WriteLine(c.ToString());
";
await TestMissingAsync(code);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;
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 TestMissing_OnMatchingFileName()
{
var code =
@"[||]class test1 { }";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMissing_Nested_OnMatchingFileName_Simple()
{
var code =
@"class outer
{
[||]class test1 { }
}";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestMatchingFileName_CaseSensitive()
{
var code =
@"[||]class Test1 { }";
await TestActionCountAsync(code, count: 2);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans1()
{
var code =
@"[|clas|]s Class1 { }
class Class2 { }";
await TestActionCountAsync(code, count: 3);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans2()
{
var code =
@"[||]class Class1 { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(14008, "https://github.com/dotnet/roslyn/issues/14008")]
public async Task TestMoveToNewFileWithFolders()
{
var code =
@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document Folders=""A\B"">
[||]class Class1 { }
class Class2 { }
</Document>
</Project>
</Workspace>";
var codeAfterMove = @"class Class2 { }
";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName,
destinationDocumentText, destinationDocumentContainers: ImmutableArray.Create("A", "B"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans3()
{
var code =
@"[|class Class1|] { }
class Class2 { }";
await TestActionCountAsync(code, count: 3);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestForSpans4()
{
var code =
@"class Class1[||] { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithNoContainerNamespace()
{
var code =
@"[||]class Class1 { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithUsingsAndNoContainerNamespace()
{
var code =
@"// Banner Text
using System;
[||]class Class1 { }
class Class2 { }";
var codeAfterMove =
@"// Banner Text
using System;
class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"// Banner Text
class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithMembers()
{
var code =
@"// Banner Text
using System;
[||]class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
class Class2 { }";
var codeAfterMove =
@"// Banner Text
class Class2 { }";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"// Banner Text
using System;
class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithMembers2()
{
var code =
@"// Banner Text
using System;
[||]class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
class Class2
{
void Print(int x)
{
Console.WriteLine(x);
}
}";
var codeAfterMove =
@"// Banner Text
using System;
class Class2
{
void Print(int x)
{
Console.WriteLine(x);
}
}";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"// Banner Text
using System;
class Class1
{
void Print(int x)
{
Console.WriteLine(x);
}
}
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveAnInterface()
{
var code =
@"[||]interface IMoveType { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "IMoveType.cs";
var destinationDocumentText = @"interface IMoveType { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveAStruct()
{
var code =
@"[||]struct MyStruct { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "MyStruct.cs";
var destinationDocumentText = @"struct MyStruct { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveAnEnum()
{
var code =
@"[||]enum MyEnum { }
class Class2 { }";
var codeAfterMove = @"class Class2 { }";
var expectedDocumentName = "MyEnum.cs";
var destinationDocumentText = @"enum MyEnum { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithContainerNamespace()
{
var code =
@"namespace N1
{
[||]class Class1 { }
class Class2 { }
}";
var codeAfterMove =
@"namespace N1
{
class Class2 { }
}";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"namespace N1
{
class Class1 { }
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithWithFileScopedNamespace()
{
var code =
@"namespace N1;
[||]class Class1 { }
class Class2 { }
";
var codeAfterMove =
@"namespace N1;
class Class2 { }
";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText =
@"namespace N1;
class Class1 { }
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_Simple()
{
var code =
@"namespace N1
{
class Class1
{
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypePreserveModifiers()
{
var code =
@"namespace N1
{
abstract class Class1
{
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
abstract partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
abstract partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(14004, "https://github.com/dotnet/roslyn/issues/14004")]
public async Task MoveNestedTypeToNewFile_Attributes1()
{
var code =
@"namespace N1
{
[Outer]
class Class1
{
[Inner]
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
[Outer]
partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
[Inner]
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")]
public async Task MoveNestedTypeToNewFile_Comments1()
{
var code =
@"namespace N1
{
/// Outer doc comment.
class Class1
{
/// Inner doc comment
[||]class Class2
{
}
}
}";
var codeAfterMove =
@"namespace N1
{
/// Outer doc comment.
partial class Class1
{
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
/// Inner doc comment
class Class2
{
}
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_Simple_DottedName()
{
var code =
@"namespace N1
{
class Class1
{
[||]class Class2 { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
}
}";
var expectedDocumentName = "Class1.Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers()
{
var code =
@"namespace N1
{
class Class1
{
private int _field1;
[||]class Class2 { }
public void Method1() { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
private int _field1;
public void Method1() { }
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers()
{
var code =
@"namespace N1
{
class Class1
{
private int _field1;
[||]class Class2 { }
public void Method1() { }
}
internal class Class3
{
private void Method1() { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
private int _field1;
public void Method1() { }
}
internal class Class3
{
private void Method1() { }
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2 { }
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveNestedTypeToNewFile_HasMembers()
{
var code =
@"namespace N1
{
class Class1
{
private int _field1;
[||]class Class2
{
private string _field1;
public void InnerMethod() { }
}
public void Method1() { }
}
}";
var codeAfterMove =
@"namespace N1
{
partial class Class1
{
private int _field1;
public void Method1() { }
}
}";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText =
@"namespace N1
{
partial class Class1
{
class Class2
{
private string _field1;
public void InnerMethod() { }
}
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
[WorkItem(13969, "https://github.com/dotnet/roslyn/issues/13969")]
public async Task MoveTypeInFileWithComplexHierarchy()
{
var code =
@"namespace OuterN1.N1
{
namespace InnerN2.N2
{
class OuterClass1
{
class InnerClass2
{
}
}
}
namespace InnerN3.N3
{
class OuterClass2
{
[||]class InnerClass2
{
class InnerClass3
{
}
}
class InnerClass4
{
}
}
class OuterClass3
{
}
}
}
namespace OuterN2.N2
{
namespace InnerN3.N3
{
class OuterClass5 {
class InnerClass6 {
}
}
}
}
";
var codeAfterMove =
@"namespace OuterN1.N1
{
namespace InnerN2.N2
{
class OuterClass1
{
class InnerClass2
{
}
}
}
namespace InnerN3.N3
{
partial class OuterClass2
{
class InnerClass4
{
}
}
class OuterClass3
{
}
}
}
namespace OuterN2.N2
{
namespace InnerN3.N3
{
class OuterClass5 {
class InnerClass6 {
}
}
}
}
";
var expectedDocumentName = "InnerClass2.cs";
var destinationDocumentText =
@"namespace OuterN1.N1
{
namespace InnerN3.N3
{
partial class OuterClass2
{
class InnerClass2
{
class InnerClass3
{
}
}
}
}
}
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeUsings1()
{
var code =
@"
// Only used by inner type.
using System;
// Unused by both types.
using System.Collections;
class Outer {
[||]class Inner {
DateTime d;
}
}";
var codeAfterMove = @"
// Only used by inner type.
// Unused by both types.
using System.Collections;
partial class Outer {
}";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"
// Only used by inner type.
using System;
// Unused by both types.
partial class Outer {
class Inner {
DateTime d;
}
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(16283, "https://github.com/dotnet/roslyn/issues/16283")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingTrivia1()
{
var code =
@"
class Outer
{
class Inner1
{
}
[||]class Inner2
{
}
}";
var codeAfterMove = @"
partial class Outer
{
class Inner1
{
}
}";
var expectedDocumentName = "Inner2.cs";
var destinationDocumentText = @"
partial class Outer
{
class Inner2
{
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestInsertFinalNewLine()
{
var code =
@"
class Outer
{
class Inner1
{
}
[||]class Inner2
{
}
}";
var codeAfterMove = @"
partial class Outer
{
class Inner1
{
}
}";
var expectedDocumentName = "Inner2.cs";
var destinationDocumentText = @"
partial class Outer
{
class Inner2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText,
onAfterWorkspaceCreated: w =>
{
w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true)));
});
}
[WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestInsertFinalNewLine2()
{
var code =
@"
class Outer
{
class Inner1
{
}
[||]class Inner2
{
}
}";
var codeAfterMove = @"
partial class Outer
{
class Inner1
{
}
}";
var expectedDocumentName = "Inner2.cs";
var destinationDocumentText = @"
partial class Outer
{
class Inner2
{
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText,
onAfterWorkspaceCreated: w =>
{
w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false)));
});
}
[WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeRemoveOuterInheritanceTypes()
{
var code =
@"
class Outer : IComparable {
[||]class Inner : IWhatever {
DateTime d;
}
}";
var codeAfterMove =
@"
partial class Outer : IComparable {
}";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"
partial class Outer
{
class Inner : IWhatever {
DateTime d;
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithDirectives1()
{
var code =
@"using System;
namespace N
{
class Program
{
static void Main()
{
}
}
}
#if true
public class [||]Inner
{
}
#endif";
var codeAfterMove =
@"using System;
namespace N
{
class Program
{
static void Main()
{
}
}
}
#if true
#endif";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"
#if true
public class Inner
{
}
#endif";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveTypeWithDirectives2()
{
var code =
@"using System;
namespace N
{
class Program
{
static void Main()
{
}
#if true
public class [||]Inner
{
}
#endif
}
}";
var codeAfterMove =
@"using System;
namespace N
{
partial class Program
{
static void Main()
{
}
#if true
#endif
}
}";
var expectedDocumentName = "Inner.cs";
var destinationDocumentText =
@"namespace N
{
partial class Program
{
#if true
public class Inner
{
}
#endif
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingBlankLines1()
{
var code =
@"// Banner Text
using System;
[||]class Class1
{
void Foo()
{
Console.WriteLine();
}
}
class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
var codeAfterMove = @"// Banner Text
using System;
class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
var expectedDocumentName = "Class1.cs";
var destinationDocumentText = @"// Banner Text
using System;
class Class1
{
void Foo()
{
Console.WriteLine();
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingBlankLines2()
{
var code =
@"// Banner Text
using System;
class Class1
{
void Foo()
{
Console.WriteLine();
}
}
[||]class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
var codeAfterMove = @"// Banner Text
using System;
class Class1
{
void Foo()
{
Console.WriteLine();
}
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
using System;
class Class2
{
void Foo()
{
Console.WriteLine();
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingCommentInContainer()
{
var code =
@"// Banner Text
using System;
class Class1
// Leading comment
{
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
// Leading comment
{
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestLeadingCommentInContainer2()
{
var code =
@"// Banner Text
using System;
class Class1
{ // Leading comment
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
{ // Leading comment
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestTrailingCommentInContainer()
{
var code =
@"// Banner Text
using System;
class Class1
{
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
// End of class document
}
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
{
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
// End of class document
}
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}
";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task TestTrailingCommentInContainer2()
{
var code =
@"// Banner Text
using System;
class Class1
{
class [||]Class2
{
}
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
} // End of class document
";
var codeAfterMove = @"// Banner Text
using System;
partial class Class1
{
void Foo()
{
Console.WriteLine();
}
public int I() => 5;
} // End of class document
";
var expectedDocumentName = "Class2.cs";
var destinationDocumentText = @"// Banner Text
partial class Class1
{
class Class2
{
}
}";
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WorkItem(50329, "https://github.com/dotnet/roslyn/issues/50329")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveRecordToNewFilePreserveUsings()
{
var code =
@"using System;
[||]record CacheContext(String Message);
class Program { }";
var codeAfterMove = @"class Program { }";
var expectedDocumentName = "CacheContext.cs";
var destinationDocumentText = @"using System;
record CacheContext(String Message);
";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MoveClassInTopLevelStatements()
{
var code = @"
using ConsoleApp1;
using System;
var c = new C();
Console.WriteLine(c.Hello);
class [||]C
{
public string Hello => ""Hello"";
}";
var codeAfterMove = @"
using ConsoleApp1;
using System;
var c = new C();
Console.WriteLine(c.Hello);
";
var expectedDocumentName = "C.cs";
var destinationDocumentText = @"class C
{
public string Hello => ""Hello"";
}";
await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public async Task MissingInTopLevelStatementsOnly()
{
var code = @"
using ConsoleApp1;
using System;
var c = new object();
[||]Console.WriteLine(c.ToString());
";
await TestMissingAsync(code);
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_ChangeNamespace.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName1()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "3B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName2()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "B.3C", "D" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentNoReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentLocalReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1(){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
public class Class1
{{
public void M1() {{ }}
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
public class Class1
{
public void M1() { }
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReferencesInVB()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""{declaredNamespace}.Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Foo.Class2 c2;
private Foo.Bar.Class3 c3;
private Foo.Bar.Baz.Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
using Class1Alias = A.B.C.Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
// Comments before declaration.
namespace [||]{declaredNamespace}
{{ // Comments after opening brace
class Class1
{{
}}
// Comments before closing brace
}} // Comments after declaration.
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
// Comments before declaration.
// Comments after opening brace
class Class1
{
}
// Comments before closing brace
// Comments after declaration.
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
global::{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1() {{ }}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
global::D1 d;
void Class1.M1() { }
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"interface Interface1
{
void M1(Interface1 c1);
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class MyClass
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass
{{
Foo.Bar.Baz.MyClass c;
}}
class MyClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class MyClass
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass
{
global::MyClass c;
}
class MyClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
";
var expectedSourceReference =
@"
namespace NS1
{
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"using System;
using Class1Alias = Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
delegate void [||]D1;
interface Class1
{{
void M1();
}}
class Class2 : Class1
{{
D1 d;
void Class1.M1() {{ }}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
interface [||]Interface1
{{
void M1(Interface1 c1);
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass : Interface1
{{
void Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
private A.Class2 c2;
private A.B.Class3 c3;
private A.B.C.Class4 c4;
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace A
{{
class Class2 {{}}
namespace B
{{
class Class3 {{}}
namespace C
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using System;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using System;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using System;
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
using System;
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Class1Alias = Class1;
namespace Foo
{{
using System;
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
using Class1Alias = Class1;
namespace Foo
{
using System;
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As A.B.C.D.Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As A.B.C.Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
public class [||]Class1
{{
}}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Class1
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class Class1
{
}
";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class MyClass
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Foo.Bar.Baz.MyClass
End Class
Public Class MyClass
End Class
End Namespace</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class MyClass
{
}
";
var expectedSourceReference =
@"Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Global.MyClass
End Class
Public Class MyClass
End Class
End Namespace";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExtensionMethodInReducedForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace {defaultNamespace}
{{
using System;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
namespace {defaultNamespace}
{{
using System;
using A.B.C;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExternsionMethodInRegularForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
using System;
using A.B.C;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ContainsBothTypeAndExternsionMethod()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
public class Class2
{{ }}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public static class Extensions
{
public static bool Foo(this Class1 c1) => true;
}
public class Class2
{ }
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
namespace A
{
public class Class1
{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithExtensionMethodReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
namespace [||]{declaredNamespace}
{{
public static class Extensions
{{
public static bool Foo(this String s) => true;
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"
using System;
namespace {defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this string s) => true;
}}
}}";
var expectedSourceReference =
$@"
Imports {defaultNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = A.B.C.Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName1()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "3B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName2()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "B.3C", "D" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentNoReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentNoReference_FileScopedNamespace()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace};
class Class1
{{
}}
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C;
class Class1
{
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentLocalReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1(){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
public class Class1
{{
public void M1() {{ }}
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
public class Class1
{
public void M1() { }
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReferencesInVB()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""{declaredNamespace}.Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Foo.Class2 c2;
private Foo.Bar.Class3 c3;
private Foo.Bar.Baz.Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
using Class1Alias = A.B.C.Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
// Comments before declaration.
namespace [||]{declaredNamespace}
{{ // Comments after opening brace
class Class1
{{
}}
// Comments before closing brace
}} // Comments after declaration.
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
// Comments before declaration.
// Comments after opening brace
class Class1
{
}
// Comments before closing brace
// Comments after declaration.
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
global::{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1() {{ }}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
global::D1 d;
void Class1.M1() { }
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"interface Interface1
{
void M1(Interface1 c1);
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class MyClass
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass
{{
Foo.Bar.Baz.MyClass c;
}}
class MyClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class MyClass
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass
{
global::MyClass c;
}
class MyClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
";
var expectedSourceReference =
@"
namespace NS1
{
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"using System;
using Class1Alias = Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
delegate void [||]D1;
interface Class1
{{
void M1();
}}
class Class2 : Class1
{{
D1 d;
void Class1.M1() {{ }}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
interface [||]Interface1
{{
void M1(Interface1 c1);
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass : Interface1
{{
void Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
private A.Class2 c2;
private A.B.Class3 c3;
private A.B.C.Class4 c4;
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace A
{{
class Class2 {{}}
namespace B
{{
class Class3 {{}}
namespace C
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using System;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using System;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using System;
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
using System;
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Class1Alias = Class1;
namespace Foo
{{
using System;
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
using Class1Alias = Class1;
namespace Foo
{
using System;
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As A.B.C.D.Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As A.B.C.Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
public class [||]Class1
{{
}}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Class1
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class Class1
{
}
";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class MyClass
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Foo.Bar.Baz.MyClass
End Class
Public Class MyClass
End Class
End Namespace</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class MyClass
{
}
";
var expectedSourceReference =
@"Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Global.MyClass
End Class
Public Class MyClass
End Class
End Namespace";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExtensionMethodInReducedForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace {defaultNamespace}
{{
using System;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
namespace {defaultNamespace}
{{
using System;
using A.B.C;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExternsionMethodInRegularForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
using System;
using A.B.C;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ContainsBothTypeAndExternsionMethod()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
public class Class2
{{ }}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public static class Extensions
{
public static bool Foo(this Class1 c1) => true;
}
public class Class2
{ }
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
namespace A
{
public class Class1
{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithExtensionMethodReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
namespace [||]{declaredNamespace}
{{
public static class Extensions
{{
public static bool Foo(this String s) => true;
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"
using System;
namespace {defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this string s) => true;
}}
}}";
var expectedSourceReference =
$@"
Imports {defaultNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = A.B.C.Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_MoveFile.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_DeclarationNotContainedInDefaultNamespace()
{
// No "move file" action because default namespace is not container of declared namespace
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var expectedFolders = new List<string[]>();
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_SingleAction1()
{
// current path is <root>\
// expected new path is <root>\B\C\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C";
var expectedFolders = new List<string[]>
{
new[] { "B", "C" }
};
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>());
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_SingleAction2()
{
// current path is <root>\
// expected new path is <root>\B\C\D\E\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>
{
new[] { "B", "C", "D", "E" }
};
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(new[] { "B", "C" }, "File2.cs"); // file2 is in <root>\B\C\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_MoveToRoot()
{
// current path is <root>\A\B\C\
// expected new path is <root>
var defaultNamespace = "";
var expectedFolders = new List<string[]>
{
Array.Empty<string>()
};
var (folder, filePath) = CreateDocumentFilePath(new[] { "A", "B", "C" });
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_MultipleAction1()
{
// current path is <root>\
// expected new paths are"
// 1. <root>\B\C\D\E\
// 2. <root>\B.C\D\E\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
expectedFolders.Add(new[] { "B.C", "D", "E" });
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(new[] { "B.C" }, "File2.cs"); // file2 is in <root>\B.C\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_MultipleAction2()
{
// current path is <root>\
// expected new paths are:
// 1. <root>\B\C\D\E\
// 2. <root>\B.C\D\E\
// 3. <root>\B\C.D\E\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
expectedFolders.Add(new[] { "B.C", "D", "E" });
expectedFolders.Add(new[] { "B", "C.D", "E" });
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(new[] { "B", "C.D" }, "File2.cs"); // file2 is in <root>\B\C.D\
var documentPath3 = CreateDocumentFilePath(new[] { "B.C" }, "File3.cs"); // file3 is in <root>\B.C\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
<Document Folders=""{documentPath3.folder}"" FilePath=""{documentPath3.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_FromOneFolderToAnother1()
{
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
expectedFolders.Add(new[] { "B.C", "D", "E" });
var (folder, filePath) = CreateDocumentFilePath(new[] { "B.C" }, "File1.cs"); // file1 is in <root>\B.C\
var documentPath2 = CreateDocumentFilePath(new[] { "B", "Foo" }, "File2.cs"); // file2 is in <root>\B\Foo\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_FromOneFolderToAnother2()
{
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
var (folder, filePath) = CreateDocumentFilePath(new[] { "Foo.Bar", "Baz" }, "File1.cs"); // file1 is in <root>\Foo.Bar\Baz\
var documentPath2 = CreateDocumentFilePath(new[] { "B", "Foo" }, "File2.cs"); // file2 is in <root>\B\Foo\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_DeclarationNotContainedInDefaultNamespace()
{
// No "move file" action because default namespace is not container of declared namespace
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var expectedFolders = new List<string[]>();
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_DeclarationNotContainedInDefaultNamespace_FileScopedNamespace()
{
// No "move file" action because default namespace is not container of declared namespace
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var expectedFolders = new List<string[]>();
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace};
class Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_SingleAction1()
{
// current path is <root>\
// expected new path is <root>\B\C\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C";
var expectedFolders = new List<string[]>
{
new[] { "B", "C" }
};
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>());
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_SingleAction2()
{
// current path is <root>\
// expected new path is <root>\B\C\D\E\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>
{
new[] { "B", "C", "D", "E" }
};
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(new[] { "B", "C" }, "File2.cs"); // file2 is in <root>\B\C\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_MoveToRoot()
{
// current path is <root>\A\B\C\
// expected new path is <root>
var defaultNamespace = "";
var expectedFolders = new List<string[]>
{
Array.Empty<string>()
};
var (folder, filePath) = CreateDocumentFilePath(new[] { "A", "B", "C" });
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_MultipleAction1()
{
// current path is <root>\
// expected new paths are"
// 1. <root>\B\C\D\E\
// 2. <root>\B.C\D\E\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
expectedFolders.Add(new[] { "B.C", "D", "E" });
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(new[] { "B.C" }, "File2.cs"); // file2 is in <root>\B.C\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_MultipleAction2()
{
// current path is <root>\
// expected new paths are:
// 1. <root>\B\C\D\E\
// 2. <root>\B.C\D\E\
// 3. <root>\B\C.D\E\
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
expectedFolders.Add(new[] { "B.C", "D", "E" });
expectedFolders.Add(new[] { "B", "C.D", "E" });
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(new[] { "B", "C.D" }, "File2.cs"); // file2 is in <root>\B\C.D\
var documentPath3 = CreateDocumentFilePath(new[] { "B.C" }, "File3.cs"); // file3 is in <root>\B.C\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
<Document Folders=""{documentPath3.folder}"" FilePath=""{documentPath3.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_FromOneFolderToAnother1()
{
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
expectedFolders.Add(new[] { "B.C", "D", "E" });
var (folder, filePath) = CreateDocumentFilePath(new[] { "B.C" }, "File1.cs"); // file1 is in <root>\B.C\
var documentPath2 = CreateDocumentFilePath(new[] { "B", "Foo" }, "File2.cs"); // file2 is in <root>\B\Foo\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_FromOneFolderToAnother2()
{
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
var (folder, filePath) = CreateDocumentFilePath(new[] { "Foo.Bar", "Baz" }, "File1.cs"); // file1 is in <root>\Foo.Bar\Baz\
var documentPath2 = CreateDocumentFilePath(new[] { "B", "Foo" }, "File2.cs"); // file2 is in <root>\B\Foo\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task MoveFile_FromOneFolderToAnother2_FileScopedNamespace()
{
var defaultNamespace = "A";
var declaredNamespace = "A.B.C.D.E";
var expectedFolders = new List<string[]>();
expectedFolders.Add(new[] { "B", "C", "D", "E" });
var (folder, filePath) = CreateDocumentFilePath(new[] { "Foo.Bar", "Baz" }, "File1.cs"); // file1 is in <root>\Foo.Bar\Baz\
var documentPath2 = CreateDocumentFilePath(new[] { "B", "Foo" }, "File2.cs"); // file2 is in <root>\B\Foo\
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace};
class Class1
{{
}}
</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo;
class Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMoveFileToMatchNamespace(code, expectedFolders);
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_NoAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnNamespaceDeclaration()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace NS
{{
class [||]Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnFirstMemberInGlobal()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class Class1
{{
}}
class [||]Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MultipleNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
namespace NS2
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnNamespace()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
class Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnFirstGlobalMember()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
namespace NS1
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NestedNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
namespace NS2
{{
class Class1
{{
}}
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_InvalidNamespaceIdentifier()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InGlobalNamespace()
{
var folders = Array.Empty<string>();
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_DefaultGlobalNamespace()
{
var folders = new[] { "A", "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InNamespaceDeclaration()
{
var folders = new[] { "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""A"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_FileNotRooted()
{
var filePath = PathUtilities.CombineAbsoluteAndRelativePaths(PathUtilities.GetPathRoot(ProjectFilePath), "Foo.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document FilePath=""{filePath}"">
namespace [||]NS
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NoDeclaration()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
[||]
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnNamespaceDeclaration()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace NS
{{
class [||]Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnNamespaceDeclaration_FileScopedNamespace()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace NS;
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnFirstMemberInGlobal()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class Class1
{{
}}
class [||]Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MultipleNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
namespace NS2
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnNamespace()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
class Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnFirstGlobalMember()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
namespace NS1
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NestedNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
namespace NS2
{{
class Class1
{{
}}
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_InvalidNamespaceIdentifier()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InGlobalNamespace()
{
var folders = Array.Empty<string>();
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_DefaultGlobalNamespace()
{
var folders = new[] { "A", "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InNamespaceDeclaration()
{
var folders = new[] { "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""A"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_FileNotRooted()
{
var filePath = PathUtilities.CombineAbsoluteAndRelativePaths(PathUtilities.GetPathRoot(ProjectFilePath), "Foo.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document FilePath=""{filePath}"">
namespace [||]NS
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NoDeclaration()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
[||]
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/Debugging/LocationInfoGetterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp;
using Microsoft.CodeAnalysis.CSharp.Debugging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging
{
[UseExportProvider]
public class LocationInfoGetterTests
{
private static async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null)
{
using var workspace = TestWorkspace.CreateCSharp(markup, parseOptions);
var testDocument = workspace.Documents.Single();
var position = testDocument.CursorPosition.Value;
var locationInfo = await LocationInfoGetter.GetInfoAsync(
workspace.CurrentSolution.Projects.Single().Documents.Single(),
position,
CancellationToken.None);
Assert.Equal(expectedName, locationInfo.Name);
Assert.Equal(expectedLineOffset, locationInfo.LineOffset);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestClass()
=> await TestAsync("class G$$oo { }", "Goo", 0);
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")]
public async Task TestMethod()
{
await TestAsync(
@"class Class
{
public static void Meth$$od()
{
}
}
", "Class.Method()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestNamespace()
{
await TestAsync(
@"namespace Namespace
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(49000, "https://github.com/dotnet/roslyn/issues/49000")]
public async Task TestFileScopedNamespace()
{
// This test behavior is incorrect. This should be Namespace.Class.Method.
// See the associated WorkItem for details.
await TestAsync(
@"namespace Namespace;
class Class
{
void Method()
{
}$$
}
", "Namespace.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestDottedNamespace()
{
await TestAsync(
@"namespace Namespace.Another
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestNestedNamespace()
{
await TestAsync(
@"namespace Namespace
{
namespace Another
{
class Class
{
void Method()
{
}$$
}
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestNestedType()
{
await TestAsync(
@"class Outer
{
class Inner
{
void Quux()
{$$
}
}
}", "Outer.Inner.Quux()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestPropertyGetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;$$
}
}
}", "Class.Property", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestPropertySetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;
}
set
{
string s = $$value;
}
}
}", "Class.Property", 9);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")]
public async Task TestField()
{
await TestAsync(
@"class Class
{
int fi$$eld;
}", "Class.field", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
public async Task TestLambdaInFieldInitializer()
{
await TestAsync(
@"class Class
{
Action<int> a = b => { in$$t c; };
}", "Class.a", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
public async Task TestMultipleFields()
{
await TestAsync(
@"class Class
{
int a1, a$$2;
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConstructor()
{
await TestAsync(
@"class C1
{
C1()
{
$$}
}
", "C1.C1()", 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestDestructor()
{
await TestAsync(
@"class C1
{
~C1()
{
$$}
}
", "C1.~C1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static int operator +(C1 x, C1 y)
{
$$return 42;
}
}
}
", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConversionOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static explicit operator N1.C2(N1.C1 x)
{
$$return null;
}
}
class C2
{
}
}
", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestEvent()
{
await TestAsync(
@"class C1
{
delegate void D1();
event D1 e1$$;
}
", "C1.e1", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextExplicitInterfaceImplementation()
{
await TestAsync(
@"interface I1
{
void M1();
}
class C1
{
void I1.M1()
{
$$}
}
", "C1.M1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextIndexer()
{
await TestAsync(
@"class C1
{
C1 this[int x]
{
get
{
$$return null;
}
}
}
", "C1.this[int x]", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestParamsParameter()
{
await TestAsync(
@"class C1
{
void M1(params int[] x) { $$ }
}
", "C1.M1(params int[] x)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestArglistParameter()
{
await TestAsync(
@"class C1
{
void M1(__arglist) { $$ }
}
", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestRefAndOutParameters()
{
await TestAsync(
@"class C1
{
void M1( ref int x, out int y )
{
$$y = x;
}
}
", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOptionalParameters()
{
await TestAsync(
@"class C1
{
void M1(int x =1)
{
$$y = x;
}
}
", "C1.M1(int x =1)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestExtensionMethod()
{
await TestAsync(
@"static class C1
{
static void M1(this int x)
{
}$$
}
", "C1.M1(this int x)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericType()
{
await TestAsync(
@"class C1<T, U>
{
static void M1() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericMethod()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericParameters()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>(C1<int, V> x, V y) { $$ }
}
", "C1.M1(C1<int, V> x, V y)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespace()
{
await TestAsync(
@"{
class Class
{
int a1, a$$2;
}
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespaceName()
{
await TestAsync(
@"namespace
{
class C1
{
int M1()
$${
}
}
}", "?.C1.M1()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingClassName()
{
await TestAsync(
@"namespace N1
class
{
int M1()
$${
}
}
}", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingMethodName()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void (ref int x)
{
$$}
}
}", "N1.C1", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingParameterList()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void M1
{
$$}
}
}", "N1.C1.M1", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelField()
{
await TestAsync(
@"$$int f1;
", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelMethod()
{
await TestAsync(
@"int M1(int x)
{
$$}
", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelStatement()
{
await TestAsync(
@"
$$System.Console.WriteLine(""Hello"")
", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CSharp;
using Microsoft.CodeAnalysis.CSharp.Debugging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging
{
[UseExportProvider]
public class LocationInfoGetterTests
{
private static async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null)
{
using var workspace = TestWorkspace.CreateCSharp(markup, parseOptions);
var testDocument = workspace.Documents.Single();
var position = testDocument.CursorPosition.Value;
var locationInfo = await LocationInfoGetter.GetInfoAsync(
workspace.CurrentSolution.Projects.Single().Documents.Single(),
position,
CancellationToken.None);
Assert.Equal(expectedName, locationInfo.Name);
Assert.Equal(expectedLineOffset, locationInfo.LineOffset);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestClass()
=> await TestAsync("class G$$oo { }", "Goo", 0);
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")]
public async Task TestMethod()
{
await TestAsync(
@"class Class
{
public static void Meth$$od()
{
}
}
", "Class.Method()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestNamespace()
{
await TestAsync(
@"namespace Namespace
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(49000, "https://github.com/dotnet/roslyn/issues/49000")]
public async Task TestFileScopedNamespace()
{
// This test behavior is incorrect. This should be Namespace.Class.Method.
// See the associated WorkItem for details.
await TestAsync(
@"namespace Namespace;
class Class
{
void Method()
{
}$$
}
", "Namespace.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestDottedNamespace()
{
await TestAsync(
@"namespace Namespace.Another
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestNestedNamespace()
{
await TestAsync(
@"namespace Namespace
{
namespace Another
{
class Class
{
void Method()
{
}$$
}
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestNestedType()
{
await TestAsync(
@"class Outer
{
class Inner
{
void Quux()
{$$
}
}
}", "Outer.Inner.Quux()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestPropertyGetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;$$
}
}
}", "Class.Property", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestPropertySetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;
}
set
{
string s = $$value;
}
}
}", "Class.Property", 9);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")]
public async Task TestField()
{
await TestAsync(
@"class Class
{
int fi$$eld;
}", "Class.field", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
public async Task TestLambdaInFieldInitializer()
{
await TestAsync(
@"class Class
{
Action<int> a = b => { in$$t c; };
}", "Class.a", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
public async Task TestMultipleFields()
{
await TestAsync(
@"class Class
{
int a1, a$$2;
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConstructor()
{
await TestAsync(
@"class C1
{
C1()
{
$$}
}
", "C1.C1()", 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestDestructor()
{
await TestAsync(
@"class C1
{
~C1()
{
$$}
}
", "C1.~C1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static int operator +(C1 x, C1 y)
{
$$return 42;
}
}
}
", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConversionOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static explicit operator N1.C2(N1.C1 x)
{
$$return null;
}
}
class C2
{
}
}
", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestEvent()
{
await TestAsync(
@"class C1
{
delegate void D1();
event D1 e1$$;
}
", "C1.e1", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextExplicitInterfaceImplementation()
{
await TestAsync(
@"interface I1
{
void M1();
}
class C1
{
void I1.M1()
{
$$}
}
", "C1.M1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextIndexer()
{
await TestAsync(
@"class C1
{
C1 this[int x]
{
get
{
$$return null;
}
}
}
", "C1.this[int x]", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestParamsParameter()
{
await TestAsync(
@"class C1
{
void M1(params int[] x) { $$ }
}
", "C1.M1(params int[] x)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestArglistParameter()
{
await TestAsync(
@"class C1
{
void M1(__arglist) { $$ }
}
", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestRefAndOutParameters()
{
await TestAsync(
@"class C1
{
void M1( ref int x, out int y )
{
$$y = x;
}
}
", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOptionalParameters()
{
await TestAsync(
@"class C1
{
void M1(int x =1)
{
$$y = x;
}
}
", "C1.M1(int x =1)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestExtensionMethod()
{
await TestAsync(
@"static class C1
{
static void M1(this int x)
{
}$$
}
", "C1.M1(this int x)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericType()
{
await TestAsync(
@"class C1<T, U>
{
static void M1() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericMethod()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericParameters()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>(C1<int, V> x, V y) { $$ }
}
", "C1.M1(C1<int, V> x, V y)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespace()
{
await TestAsync(
@"{
class Class
{
int a1, a$$2;
}
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespaceName()
{
await TestAsync(
@"namespace
{
class C1
{
int M1()
$${
}
}
}", "?.C1.M1()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingClassName()
{
await TestAsync(
@"namespace N1
class
{
int M1()
$${
}
}
}", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingMethodName()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void (ref int x)
{
$$}
}
}", "N1.C1", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingParameterList()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void M1
{
$$}
}
}", "N1.C1.M1", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelField()
{
await TestAsync(
@"$$int f1;
", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelMethod()
{
await TestAsync(
@"int M1(int x)
{
$$}
", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelStatement()
{
await TestAsync(
@"
$$System.Console.WriteLine(""Hello"")
", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/CodeRefactorings/MoveType/CSharpMoveTypeService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.MoveType;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveType
{
[ExportLanguageService(typeof(IMoveTypeService), LanguageNames.CSharp), Shared]
internal class CSharpMoveTypeService :
AbstractMoveTypeService<CSharpMoveTypeService, BaseTypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, MemberDeclarationSyntax, CompilationUnitSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpMoveTypeService()
{
}
protected override async Task<BaseTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
=> await document.TryGetRelevantNodeAsync<BaseTypeDeclarationSyntax>(textSpan, 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.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.MoveType;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveType
{
[ExportLanguageService(typeof(IMoveTypeService), LanguageNames.CSharp), Shared]
internal class CSharpMoveTypeService :
AbstractMoveTypeService<CSharpMoveTypeService, BaseTypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, MemberDeclarationSyntax, CompilationUnitSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpMoveTypeService()
{
}
protected override async Task<BaseTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
=> await document.TryGetRelevantNodeAsync<BaseTypeDeclarationSyntax>(textSpan, cancellationToken).ConfigureAwait(false);
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeNamespace;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace
{
[ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeNamespaceService :
AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeNamespaceService()
{
}
protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync(
Document document,
SyntaxNode container,
CancellationToken cancellationToken)
{
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles
|| document.IsGeneratedCode(cancellationToken))
{
return default;
}
TextSpan containerSpan;
if (container is BaseNamespaceDeclarationSyntax)
{
containerSpan = container.Span;
}
else if (container is CompilationUnitSyntax)
{
// A compilation unit as container means user want to move all its members from global to some namespace.
// We use an empty span to indicate this case.
containerSpan = default;
}
else
{
throw ExceptionUtilities.Unreachable;
}
if (!IsSupportedLinkedDocument(document, out var allDocumentIds))
return default;
return await TryGetApplicableContainersFromAllDocumentsAsync(
document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false);
}
protected override string GetDeclaredNamespace(SyntaxNode container)
{
if (container is CompilationUnitSyntax)
return string.Empty;
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl);
throw ExceptionUtilities.Unreachable;
}
protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container)
{
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return namespaceDecl.Members;
if (container is CompilationUnitSyntax compilationUnit)
return compilationUnit.Members;
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed.
/// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on
/// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead.
/// </summary>
/// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from
/// `SymbolFinder.FindReferencesAsync`.</param>
/// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference
/// will be replaced with given namespace in the new node.</param>
/// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param>
/// <param name="newNode">The replacement node.</param>
public override bool TryGetReplacementReferenceSyntax(
SyntaxNode reference,
ImmutableArray<string> newNamespaceParts,
ISyntaxFactsService syntaxFacts,
[NotNullWhen(returnValue: true)] out SyntaxNode? oldNode,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (reference is not SimpleNameSyntax nameRef)
{
oldNode = newNode = null;
return false;
}
// A few different cases are handled here:
//
// 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done.
// And both old and new will point to the original reference.
//
// 2. When the new namespace is not specified, we don't need to change the qualified part of reference.
// Both old and new will point to the qualified reference.
//
// 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace.
// As a result, we need replace qualified reference with the simple name.
//
// 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global
// namespace. We need to replace the qualified reference with a new qualified reference (which is qualified
// with new namespace.)
//
// Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases.
if (syntaxFacts.IsRightSideOfQualifiedName(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) ||
syntaxFacts.IsNameOfMemberBindingExpression(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref)
{
// This is the case where the reference is the right most part of a qualified name in `cref`.
// for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`.
// This is the form of `cref` we need to handle as a spacial case when changing namespace name or
// changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the
// same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`.
var container = qualifiedCref.Container;
var aliasQualifier = GetAliasQualifier(container);
if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
// We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`,
// which is a alias qualified simple name, similar to the regular case above.
oldNode = qualifiedCref;
newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!);
}
else
{
// if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`,
// which is just a regular namespace node, no cref node involve here.
oldNode = container;
newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
}
return true;
}
// Simple name reference, nothing to be done.
// The name will be resolved by adding proper import.
oldNode = newNode = nameRef;
return false;
}
private static bool TryGetGlobalQualifiedName(
ImmutableArray<string> newNamespaceParts,
SimpleNameSyntax nameNode,
string? aliasQualifier,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (IsGlobalNamespace(newNamespaceParts))
{
// If new namespace is "", then name will be declared in global namespace.
// We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified)
var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia());
return true;
}
newNode = null;
return false;
}
/// <summary>
/// Try to change the namespace declaration based on the following rules:
/// - if neither declared nor target namespace are "" (i.e. global namespace),
/// then we try to change the name of the namespace.
/// - if declared namespace is "", then we try to move all types declared
/// in global namespace in the document into a new namespace declaration.
/// - if target namespace is "", then we try to move all members in declared
/// namespace to global namespace (i.e. remove the namespace declaration).
/// </summary>
protected override CompilationUnitSyntax ChangeNamespaceDeclaration(
CompilationUnitSyntax root,
ImmutableArray<string> declaredNamespaceParts,
ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault);
var container = root.GetAnnotatedNodes(ContainerAnnotation).Single();
if (container is CompilationUnitSyntax compilationUnit)
{
// Move everything from global namespace to a namespace declaration
Debug.Assert(IsGlobalNamespace(declaredNamespaceParts));
return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts);
}
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
{
// Move everything to global namespace
if (IsGlobalNamespace(targetNamespaceParts))
return MoveMembersFromNamespaceToGlobal(root, namespaceDecl);
// Change namespace name
return root.ReplaceNode(
namespaceDecl,
namespaceDecl.WithName(
CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation))
.WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added
}
throw ExceptionUtilities.Unreachable;
}
private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal(
CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl)
{
var (namespaceOpeningTrivia, namespaceClosingTrivia) =
GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl);
var members = namespaceDecl.Members;
var eofToken = root.EndOfFileToken
.WithAdditionalAnnotations(WarningAnnotation);
// Try to preserve trivia from original namespace declaration.
// If there's any member inside the declaration, we attach them to the
// first and last member, otherwise, simply attach all to the EOF token.
if (members.Count > 0)
{
var first = members.First();
var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia);
members = members.Replace(first, firstWithTrivia);
var last = members.Last();
var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia);
members = members.Replace(last, lastWithTrivia);
}
else
{
eofToken = eofToken.WithPrependedLeadingTrivia(
namespaceOpeningTrivia.Concat(namespaceClosingTrivia));
}
// Moving inner imports out of the namespace declaration can lead to a break in semantics.
// For example:
//
// namespace A.B.C
// {
// using D.E.F;
// }
//
// The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside,
// it may fail to resolve.
return root.Update(
root.Externs.AddRange(namespaceDecl.Externs),
root.Usings.AddRange(namespaceDecl.Usings),
root.AttributeLists,
root.Members.ReplaceRange(namespaceDecl, members),
eofToken);
}
private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax));
var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration(
name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithAdditionalAnnotations(WarningAnnotation),
externs: default,
usings: default,
members: compilationUnit.Members);
return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl))
.WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added
}
/// <summary>
/// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace
/// declaration or a compilation unit, contain no partial declarations and meet the following additional
/// requirements:
///
/// - If a namespace declaration:
/// 1. It doesn't contain or is nested in other namespace declarations
/// 2. The name of the namespace is valid (i.e. no errors)
///
/// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration
/// inside (i.e. all members are declared in global namespace)
/// </summary>
protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(syntaxRoot);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
SyntaxNode? container = null;
// Empty span means that user wants to move all types declared in the document to a new namespace.
// This action is only supported when everything in the document is declared in global namespace,
// which we use the number of namespace declaration nodes to decide.
if (span.IsEmpty)
{
if (ContainsNamespaceDeclaration(compilationUnit))
return null;
container = compilationUnit;
}
else
{
// Otherwise, the span should contain a namespace declaration node, which must be the only one
// in the entire syntax spine to enable the change namespace operation.
if (!compilationUnit.Span.Contains(span))
return null;
var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true);
var namespaceDecl = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().SingleOrDefault();
if (namespaceDecl == null)
return null;
if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error))
return null;
if (ContainsNamespaceDeclaration(node))
return null;
container = namespaceDecl;
}
var containsPartial =
await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false);
if (containsPartial)
return null;
return container;
static bool ContainsNamespaceDeclaration(SyntaxNode node)
=> node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax)
.OfType<BaseNamespaceDeclarationSyntax>().Any();
}
private static string? GetAliasQualifier(SyntaxNode? name)
{
while (true)
{
switch (name)
{
case QualifiedNameSyntax qualifiedNameNode:
name = qualifiedNameNode.Left;
continue;
case MemberAccessExpressionSyntax memberAccessNode:
name = memberAccessNode.Expression;
continue;
case AliasQualifiedNameSyntax aliasQualifiedNameNode:
return aliasQualifiedNameNode.Alias.Identifier.ValueText;
}
return null;
}
}
private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece);
}
private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
{
return aliasQualifier == null
? (NameSyntax)namePiece
: SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
}
return SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1),
namePiece);
}
/// <summary>
/// return trivia attached to namespace declaration.
/// Leading trivia of the node and trivia around opening brace, as well as
/// trivia around closing brace are concatenated together respectively.
/// </summary>
private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia)
GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace)
{
var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
openingBuilder.AddRange(baseNamespace.GetLeadingTrivia());
if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration)
{
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia);
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia);
}
else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace)
{
openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia);
}
return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeNamespace;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace
{
[ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeNamespaceService :
AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeNamespaceService()
{
}
protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync(
Document document,
SyntaxNode container,
CancellationToken cancellationToken)
{
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles
|| document.IsGeneratedCode(cancellationToken))
{
return default;
}
TextSpan containerSpan;
if (container is BaseNamespaceDeclarationSyntax)
{
containerSpan = container.Span;
}
else if (container is CompilationUnitSyntax)
{
// A compilation unit as container means user want to move all its members from global to some namespace.
// We use an empty span to indicate this case.
containerSpan = default;
}
else
{
throw ExceptionUtilities.Unreachable;
}
if (!IsSupportedLinkedDocument(document, out var allDocumentIds))
return default;
return await TryGetApplicableContainersFromAllDocumentsAsync(
document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false);
}
protected override string GetDeclaredNamespace(SyntaxNode container)
{
if (container is CompilationUnitSyntax)
return string.Empty;
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl);
throw ExceptionUtilities.Unreachable;
}
protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container)
{
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
return namespaceDecl.Members;
if (container is CompilationUnitSyntax compilationUnit)
return compilationUnit.Members;
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed.
/// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on
/// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead.
/// </summary>
/// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from
/// `SymbolFinder.FindReferencesAsync`.</param>
/// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference
/// will be replaced with given namespace in the new node.</param>
/// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param>
/// <param name="newNode">The replacement node.</param>
public override bool TryGetReplacementReferenceSyntax(
SyntaxNode reference,
ImmutableArray<string> newNamespaceParts,
ISyntaxFactsService syntaxFacts,
[NotNullWhen(returnValue: true)] out SyntaxNode? oldNode,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (reference is not SimpleNameSyntax nameRef)
{
oldNode = newNode = null;
return false;
}
// A few different cases are handled here:
//
// 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done.
// And both old and new will point to the original reference.
//
// 2. When the new namespace is not specified, we don't need to change the qualified part of reference.
// Both old and new will point to the qualified reference.
//
// 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace.
// As a result, we need replace qualified reference with the simple name.
//
// 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global
// namespace. We need to replace the qualified reference with a new qualified reference (which is qualified
// with new namespace.)
//
// Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases.
if (syntaxFacts.IsRightSideOfQualifiedName(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) ||
syntaxFacts.IsNameOfMemberBindingExpression(nameRef))
{
RoslynDebug.Assert(nameRef.Parent is object);
oldNode = nameRef.Parent;
var aliasQualifier = GetAliasQualifier(oldNode);
if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia());
}
// We might lose some trivia associated with children of `oldNode`.
newNode = newNode.WithTriviaFrom(oldNode);
return true;
}
else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref)
{
// This is the case where the reference is the right most part of a qualified name in `cref`.
// for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`.
// This is the form of `cref` we need to handle as a spacial case when changing namespace name or
// changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the
// same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`.
var container = qualifiedCref.Container;
var aliasQualifier = GetAliasQualifier(container);
if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode))
{
// We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`,
// which is a alias qualified simple name, similar to the regular case above.
oldNode = qualifiedCref;
newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!);
}
else
{
// if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`,
// which is just a regular namespace node, no cref node involve here.
oldNode = container;
newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1);
}
return true;
}
// Simple name reference, nothing to be done.
// The name will be resolved by adding proper import.
oldNode = newNode = nameRef;
return false;
}
private static bool TryGetGlobalQualifiedName(
ImmutableArray<string> newNamespaceParts,
SimpleNameSyntax nameNode,
string? aliasQualifier,
[NotNullWhen(returnValue: true)] out SyntaxNode? newNode)
{
if (IsGlobalNamespace(newNamespaceParts))
{
// If new namespace is "", then name will be declared in global namespace.
// We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified)
var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia());
return true;
}
newNode = null;
return false;
}
/// <summary>
/// Try to change the namespace declaration based on the following rules:
/// - if neither declared nor target namespace are "" (i.e. global namespace),
/// then we try to change the name of the namespace.
/// - if declared namespace is "", then we try to move all types declared
/// in global namespace in the document into a new namespace declaration.
/// - if target namespace is "", then we try to move all members in declared
/// namespace to global namespace (i.e. remove the namespace declaration).
/// </summary>
protected override CompilationUnitSyntax ChangeNamespaceDeclaration(
CompilationUnitSyntax root,
ImmutableArray<string> declaredNamespaceParts,
ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault);
var container = root.GetAnnotatedNodes(ContainerAnnotation).Single();
if (container is CompilationUnitSyntax compilationUnit)
{
// Move everything from global namespace to a namespace declaration
Debug.Assert(IsGlobalNamespace(declaredNamespaceParts));
return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts);
}
if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
{
// Move everything to global namespace
if (IsGlobalNamespace(targetNamespaceParts))
return MoveMembersFromNamespaceToGlobal(root, namespaceDecl);
// Change namespace name
return root.ReplaceNode(
namespaceDecl,
namespaceDecl.WithName(
CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation))
.WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added
}
throw ExceptionUtilities.Unreachable;
}
private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal(
CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl)
{
var (namespaceOpeningTrivia, namespaceClosingTrivia) =
GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl);
var members = namespaceDecl.Members;
var eofToken = root.EndOfFileToken
.WithAdditionalAnnotations(WarningAnnotation);
// Try to preserve trivia from original namespace declaration.
// If there's any member inside the declaration, we attach them to the
// first and last member, otherwise, simply attach all to the EOF token.
if (members.Count > 0)
{
var first = members.First();
var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia);
members = members.Replace(first, firstWithTrivia);
var last = members.Last();
var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia);
members = members.Replace(last, lastWithTrivia);
}
else
{
eofToken = eofToken.WithPrependedLeadingTrivia(
namespaceOpeningTrivia.Concat(namespaceClosingTrivia));
}
// Moving inner imports out of the namespace declaration can lead to a break in semantics.
// For example:
//
// namespace A.B.C
// {
// using D.E.F;
// }
//
// The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside,
// it may fail to resolve.
return root.Update(
root.Externs.AddRange(namespaceDecl.Externs),
root.Usings.AddRange(namespaceDecl.Usings),
root.AttributeLists,
root.Members.ReplaceRange(namespaceDecl, members),
eofToken);
}
private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts)
{
Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax));
var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration(
name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1)
.WithAdditionalAnnotations(WarningAnnotation),
externs: default,
usings: default,
members: compilationUnit.Members);
return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl))
.WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added
}
/// <summary>
/// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace
/// declaration or a compilation unit, contain no partial declarations and meet the following additional
/// requirements:
///
/// - If a namespace declaration:
/// 1. It doesn't contain or is nested in other namespace declarations
/// 2. The name of the namespace is valid (i.e. no errors)
///
/// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration
/// inside (i.e. all members are declared in global namespace)
/// </summary>
protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(syntaxRoot);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
SyntaxNode? container = null;
// Empty span means that user wants to move all types declared in the document to a new namespace.
// This action is only supported when everything in the document is declared in global namespace,
// which we use the number of namespace declaration nodes to decide.
if (span.IsEmpty)
{
if (ContainsNamespaceDeclaration(compilationUnit))
return null;
container = compilationUnit;
}
else
{
// Otherwise, the span should contain a namespace declaration node, which must be the only one
// in the entire syntax spine to enable the change namespace operation.
if (!compilationUnit.Span.Contains(span))
return null;
var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true);
var namespaceDecl = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().SingleOrDefault();
if (namespaceDecl == null)
return null;
if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error))
return null;
if (ContainsNamespaceDeclaration(node))
return null;
container = namespaceDecl;
}
var containsPartial =
await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false);
if (containsPartial)
return null;
return container;
static bool ContainsNamespaceDeclaration(SyntaxNode node)
=> node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax)
.OfType<BaseNamespaceDeclarationSyntax>().Any();
}
private static string? GetAliasQualifier(SyntaxNode? name)
{
while (true)
{
switch (name)
{
case QualifiedNameSyntax qualifiedNameNode:
name = qualifiedNameNode.Left;
continue;
case MemberAccessExpressionSyntax memberAccessNode:
name = memberAccessNode.Expression;
continue;
case AliasQualifiedNameSyntax aliasQualifiedNameNode:
return aliasQualifiedNameNode.Alias.Identifier.ValueText;
}
return null;
}
}
private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece);
}
private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index)
{
var part = namespaceParts[index].EscapeIdentifier();
Debug.Assert(part.Length > 0);
var namePiece = SyntaxFactory.IdentifierName(part);
if (index == 0)
{
return aliasQualifier == null
? (NameSyntax)namePiece
: SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece);
}
return SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1),
namePiece);
}
/// <summary>
/// return trivia attached to namespace declaration.
/// Leading trivia of the node and trivia around opening brace, as well as
/// trivia around closing brace are concatenated together respectively.
/// </summary>
private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia)
GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace)
{
var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance();
openingBuilder.AddRange(baseNamespace.GetLeadingTrivia());
if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration)
{
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia);
openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia);
closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia);
}
else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace)
{
openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia);
}
return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree());
}
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpSyncNamespaceCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.SyncNamespace
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SyncNamespace), Shared]
internal sealed class CSharpSyncNamespaceCodeRefactoringProvider
: AbstractSyncNamespaceCodeRefactoringProvider<NamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSyncNamespaceCodeRefactoringProvider()
{
}
protected override async Task<SyntaxNode> TryGetApplicableInvocationNodeAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
if (!span.IsEmpty)
{
return null;
}
var position = span.Start;
var compilationUnit = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var namespaceDecls = compilationUnit.DescendantNodes(n => n is CompilationUnitSyntax || n is NamespaceDeclarationSyntax)
.OfType<NamespaceDeclarationSyntax>().ToImmutableArray();
if (namespaceDecls.Length == 1 && compilationUnit.Members.Count == 1)
{
var namespaceDeclaration = namespaceDecls[0];
if (namespaceDeclaration.Name.Span.IntersectsWith(position))
{
return namespaceDeclaration;
}
}
if (namespaceDecls.Length == 0)
{
var firstMemberDeclarationName = compilationUnit.Members.FirstOrDefault().GetNameToken();
if (firstMemberDeclarationName != default
&& firstMemberDeclarationName.Span.IntersectsWith(position))
{
return compilationUnit;
}
}
return null;
}
protected override string EscapeIdentifier(string identifier)
=> identifier.EscapeIdentifier();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.SyncNamespace
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SyncNamespace), Shared]
internal sealed class CSharpSyncNamespaceCodeRefactoringProvider
: AbstractSyncNamespaceCodeRefactoringProvider<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSyncNamespaceCodeRefactoringProvider()
{
}
protected override async Task<SyntaxNode> TryGetApplicableInvocationNodeAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
if (!span.IsEmpty)
return null;
var position = span.Start;
var compilationUnit = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var namespaceDecls = compilationUnit.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax)
.OfType<BaseNamespaceDeclarationSyntax>().ToImmutableArray();
if (namespaceDecls.Length == 1 && compilationUnit.Members.Count == 1)
{
var namespaceDeclaration = namespaceDecls[0];
if (namespaceDeclaration.Name.Span.IntersectsWith(position))
return namespaceDeclaration;
}
if (namespaceDecls.Length == 0)
{
var firstMemberDeclarationName = compilationUnit.Members.FirstOrDefault().GetNameToken();
if (firstMemberDeclarationName != default
&& firstMemberDeclarationName.Span.IntersectsWith(position))
{
return compilationUnit;
}
}
return null;
}
protected override string EscapeIdentifier(string identifier)
=> identifier.EscapeIdentifier();
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.CSharp.LanguageServices
{
internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts
{
internal static readonly CSharpSyntaxFacts Instance = new();
protected CSharpSyntaxFacts()
{
}
public bool IsCaseSensitive => true;
public StringComparer StringComparer { get; } = StringComparer.Ordinal;
public SyntaxTrivia ElasticMarker
=> SyntaxFactory.ElasticMarker;
public SyntaxTrivia ElasticCarriageReturnLineFeed
=> SyntaxFactory.ElasticCarriageReturnLineFeed;
public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance;
protected override IDocumentationCommentService DocumentationCommentService
=> CSharpDocumentationCommentService.Instance;
public bool SupportsIndexingInitializer(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6;
public bool SupportsThrowExpression(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsLocalFunctionDeclaration(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsRecord(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9;
public bool SupportsRecordStruct(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove();
public SyntaxToken ParseToken(string text)
=> SyntaxFactory.ParseToken(text);
public SyntaxTriviaList ParseLeadingTrivia(string text)
=> SyntaxFactory.ParseLeadingTrivia(text);
public string EscapeIdentifier(string identifier)
{
var nullIndex = identifier.IndexOf('\0');
if (nullIndex >= 0)
{
identifier = identifier.Substring(0, nullIndex);
}
var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
return needsEscaping ? "@" + identifier : identifier;
}
public bool IsVerbatimIdentifier(SyntaxToken token)
=> token.IsVerbatimIdentifier();
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsReservedKeyword(SyntaxToken token)
=> SyntaxFacts.IsReservedKeyword(token.Kind());
public bool IsContextualKeyword(SyntaxToken token)
=> SyntaxFacts.IsContextualKeyword(token.Kind());
public bool IsPreprocessorKeyword(SyntaxToken token)
=> SyntaxFacts.IsPreprocessorKeyword(token.Kind());
public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
=> syntaxTree.IsPreProcessorDirectiveContext(
position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree == null)
{
return false;
}
return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is DirectiveTriviaSyntax;
public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info)
{
if (node is LineDirectiveTriviaSyntax lineDirective)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default;
return false;
}
public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsRightSideOfQualifiedName();
}
public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsSimpleMemberAccessExpressionName();
}
public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node;
public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberBindingExpressionName();
}
[return: NotNullIfNotNull("node")]
public SyntaxNode? GetStandaloneExpression(SyntaxNode? node)
=> node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node;
public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node)
=> node.GetRootConditionalAccessExpression();
public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) &&
objectCreation.Type == node;
public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is DeclarationExpressionSyntax;
public bool IsAttributeName(SyntaxNode node)
=> SyntaxFacts.IsAttributeName(node);
public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node)
{
return node is ParenthesizedLambdaExpressionSyntax ||
node is SimpleLambdaExpressionSyntax ||
node is AnonymousMethodExpressionSyntax;
}
public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node is ArgumentSyntax arg && arg.NameColon != null;
public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.CheckParent<NameColonSyntax>(p => p.Name == node);
public SyntaxToken? GetNameOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Identifier;
public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Default;
public SyntaxNode? GetParameterList(SyntaxNode node)
=> node.GetParameterList();
public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList);
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName)
{
return genericName is GenericNameSyntax csharpGenericName
? csharpGenericName.Identifier
: default;
}
public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) &&
usingDirective.Name == node;
public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null;
public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is ForEachVariableStatementSyntax;
public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node)
=> node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction();
public Location GetDeconstructionReferenceLocation(SyntaxNode node)
{
return node switch
{
AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(),
ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(),
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
}
public bool IsStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node)
{
if (node is BlockSyntax ||
node is ArrowExpressionClauseSyntax)
{
return node.Parent is BaseMethodDeclarationSyntax ||
node.Parent is AccessorDeclarationSyntax;
}
return false;
}
public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node)
=> (node as ReturnStatementSyntax)?.Expression;
public bool IsThisConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsBaseConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsQueryKeyword(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.FromKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.InKeyword:
return token.Parent is QueryClauseSyntax;
case SyntaxKind.ByKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.SelectKeyword:
return token.Parent is SelectOrGroupClauseSyntax;
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return token.Parent is OrderingSyntax;
case SyntaxKind.IntoKeyword:
return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation);
default:
return false;
}
}
public bool IsThrowExpression(SyntaxNode node)
=> node.Kind() == SyntaxKind.ThrowExpression;
public bool IsPredefinedType(SyntaxToken token)
=> TryGetPredefinedType(token, out _);
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
=> TryGetPredefinedType(token, out var actualType) && actualType == type;
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private static PredefinedType GetPredefinedType(SyntaxToken token)
{
return (SyntaxKind)token.RawKind switch
{
SyntaxKind.BoolKeyword => PredefinedType.Boolean,
SyntaxKind.ByteKeyword => PredefinedType.Byte,
SyntaxKind.SByteKeyword => PredefinedType.SByte,
SyntaxKind.IntKeyword => PredefinedType.Int32,
SyntaxKind.UIntKeyword => PredefinedType.UInt32,
SyntaxKind.ShortKeyword => PredefinedType.Int16,
SyntaxKind.UShortKeyword => PredefinedType.UInt16,
SyntaxKind.LongKeyword => PredefinedType.Int64,
SyntaxKind.ULongKeyword => PredefinedType.UInt64,
SyntaxKind.FloatKeyword => PredefinedType.Single,
SyntaxKind.DoubleKeyword => PredefinedType.Double,
SyntaxKind.DecimalKeyword => PredefinedType.Decimal,
SyntaxKind.StringKeyword => PredefinedType.String,
SyntaxKind.CharKeyword => PredefinedType.Char,
SyntaxKind.ObjectKeyword => PredefinedType.Object,
SyntaxKind.VoidKeyword => PredefinedType.Void,
_ => PredefinedType.None,
};
}
public bool IsPredefinedOperator(SyntaxToken token)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None;
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op;
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private static PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanToken:
return PredefinedOperator.LessThan;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
=> SyntaxFacts.GetText((SyntaxKind)kind);
public bool IsIdentifierStartCharacter(char c)
=> SyntaxFacts.IsIdentifierStartCharacter(c);
public bool IsIdentifierPartCharacter(char c)
=> SyntaxFacts.IsIdentifierPartCharacter(c);
public bool IsIdentifierEscapeCharacter(char c)
=> c == '@';
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c) => false;
public bool IsStartOfUnicodeEscapeSequence(char c)
=> c == '\\';
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
return true;
default:
return false;
}
}
public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token)
=> token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.IsKind(SyntaxKind.NumericLiteralExpression) == true;
public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent)
{
var typedToken = token;
var typedParent = parent;
if (typedParent.IsKind(SyntaxKind.IdentifierName))
{
TypeSyntax? declaredType = null;
if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl))
{
declaredType = varDecl.Type;
}
else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl))
{
declaredType = fieldDecl.Declaration.Type;
}
return declaredType == typedParent && typedToken.ValueText == "var";
}
return false;
}
public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent)
{
if (parent is ExpressionSyntax typedParent)
{
if (SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
typedParent.IsKind(SyntaxKind.IdentifierName) &&
token.ValueText == "dynamic")
{
return true;
}
}
return false;
}
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
// In the order by clause a comma might be bound to ThenBy or ThenByDescending
if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause))
{
return true;
}
return false;
}
public void GetPartsOfConditionalAccessExpression(
SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull)
{
var conditionalAccess = (ConditionalAccessExpressionSyntax)node;
expression = conditionalAccess.Expression;
operatorToken = conditionalAccess.OperatorToken;
whenNotNull = conditionalAccess.WhenNotNull;
}
public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is PostfixUnaryExpressionSyntax;
public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberBindingExpressionSyntax;
public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression;
public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity)
{
name = null;
arity = 0;
if (node is SimpleNameSyntax simpleName)
{
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
}
public bool LooksGeneric(SyntaxNode simpleName)
=> simpleName.IsKind(SyntaxKind.GenericName) ||
simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken;
public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node)
=> (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression;
public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node)
=> ((MemberBindingExpressionSyntax)node).Name;
public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget)
=> (node as MemberAccessExpressionSyntax)?.Expression;
public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList)
{
var elementAccess = node as ElementAccessExpressionSyntax;
expression = elementAccess?.Expression;
argumentList = elementAccess?.ArgumentList;
}
public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node)
=> (node as InterpolationSyntax)?.Expression;
public bool IsInStaticContext(SyntaxNode node)
=> node.IsInStaticContext();
public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.BaseList);
public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node)
=> (node as ArgumentSyntax)?.Expression;
public RefKind GetRefKindOfArgument(SyntaxNode? node)
=> (node as ArgumentSyntax).GetRefKind();
public bool IsArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Argument);
public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node)
{
return node is ArgumentSyntax argument &&
argument.RefOrOutKeyword.Kind() == SyntaxKind.None &&
argument.NameColon == null;
}
public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsInConstantContext();
public bool IsInConstructor(SyntaxNode node)
=> node.GetAncestor<ConstructorDeclarationSyntax>() != null;
public bool IsUnsafeContext(SyntaxNode node)
=> node.IsUnsafeContext();
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
=> ((AttributeSyntax)node).Name;
public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node)
=> ((ParenthesizedExpressionSyntax)node).Expression;
public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier();
public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node)
=> throw ExceptionUtilities.Unreachable;
public SyntaxToken FindTokenOnLeftOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public SyntaxToken FindTokenOnRightOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IdentifierName) &&
node.IsParentKind(SyntaxKind.NameColon) &&
node.Parent.IsParentKind(SyntaxKind.Subpattern);
public bool IsPropertyPatternClause(SyntaxNode node)
=> node.Kind() == SyntaxKind.PropertyPatternClause;
public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> IsMemberInitializerNamedAssignmentIdentifier(node, out _);
public bool IsMemberInitializerNamedAssignmentIdentifier(
[NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance)
{
initializedInstance = null;
if (node is IdentifierNameSyntax identifier &&
identifier.IsLeftSideOfAssignExpression())
{
if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression))
{
var withInitializer = identifier.Parent.GetRequiredParent();
initializedInstance = withInitializer.GetRequiredParent();
return true;
}
else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression))
{
var objectInitializer = identifier.Parent.GetRequiredParent();
if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax)
{
initializedInstance = objectInitializer.Parent;
return true;
}
else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment))
{
initializedInstance = assignment.Left;
return true;
}
}
}
return false;
}
public bool IsElementAccessExpression(SyntaxNode? node)
=> node.IsKind(SyntaxKind.ElementAccessExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false)
=> node.ConvertToSingleLine(useElasticTrivia);
public void GetPartsOfParenthesizedExpression(
SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen)
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)node;
openParen = parenthesizedExpression.OpenParenToken;
expression = parenthesizedExpression.Expression;
closeParen = parenthesizedExpression.CloseParenToken;
}
public bool IsIndexerMemberCRef(SyntaxNode? node)
=> node.IsKind(SyntaxKind.IndexerMemberCref);
public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
var kind = node.Kind();
if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax ||
node is EnumMemberDeclarationSyntax ||
node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseNamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
private const string dotToken = ".";
public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string?>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent is BaseNamespaceDeclarationSyntax)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string? GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.IncompleteMember:
return missingTokenPlaceholder;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string? name = null;
if (node is MemberDeclarationSyntax memberDeclaration)
{
if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration)
{
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
else
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember);
name = "?";
}
}
}
else
{
if (node is VariableDeclaratorSyntax fieldDeclarator)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (var i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: true, methodLevel: true);
return list;
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: false, methodLevel: true);
return list;
}
public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node?.Kind() == SyntaxKind.ClassDeclaration;
public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node is BaseNamespaceDeclarationSyntax;
public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node)
=> (node as BaseNamespaceDeclarationSyntax)?.Name;
public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration)
=> ((TypeDeclarationSyntax)typeDeclaration).Members;
public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration)
=> ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members;
public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit)
=> ((CompilationUnitSyntax)compilationUnit).Members;
public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration)
=> ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings;
public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit)
=> ((CompilationUnitSyntax)compilationUnit).Usings;
private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel)
{
Debug.Assert(topLevel || methodLevel);
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (topLevel)
{
list.Add(member);
}
AppendMembers(member, list, topLevel, methodLevel);
continue;
}
if (methodLevel && IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default;
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default;
}
// TODO: currently we only support method for now
if (member is BaseMethodDeclarationSyntax method)
{
if (method.Body == null)
{
return default;
}
return GetBlockBodySpan(method.Body);
}
return default;
}
public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span)
{
switch (node)
{
case ConstructorDeclarationSyntax constructor:
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
case BaseMethodDeclarationSyntax method:
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
case BasePropertyDeclarationSyntax property:
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
case EnumMemberDeclarationSyntax @enum:
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
case BaseFieldDeclarationSyntax field:
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private static TextSpan GetBlockBodySpan(BlockSyntax body)
=> TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
public SyntaxNode? TryGetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
if (parent is MemberAccessExpressionSyntax memberAccess)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is QualifiedNameSyntax qualifiedName)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
if (parent is ObjectCreationExpressionSyntax objectCreation)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
if (!(parent is NameSyntax))
{
break;
}
node = parent;
}
if (node is VarPatternSyntax)
{
return node;
}
// Patterns are never bindable (though their constituent types/exprs may be).
return node is PatternSyntax ? null : node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken)
{
if (!(root is CompilationUnitSyntax compilationUnit))
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
switch (member)
{
case ConstructorDeclarationSyntax constructor:
constructors.Add(constructor);
continue;
case BaseNamespaceDeclarationSyntax @namespace:
AppendConstructors(@namespace.Members, constructors, cancellationToken);
break;
case ClassDeclarationSyntax @class:
AppendConstructors(@class.Members, constructors, cancellationToken);
break;
case RecordDeclarationSyntax record:
AppendConstructors(record.Members, constructors, cancellationToken);
break;
case StructDeclarationSyntax @struct:
AppendConstructors(@struct.Members, constructors, cancellationToken);
break;
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.openBrace;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default;
return false;
}
public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return trivia.FullSpan;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return default;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return default;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax branch)
{
return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default;
}
}
}
}
return default;
}
public string GetNameForArgument(SyntaxNode? argument)
=> (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty;
public string GetNameForAttributeArgument(SyntaxNode? argument)
=> (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty;
public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfDot();
public SyntaxNode? GetRightSideOfDot(SyntaxNode? node)
{
return (node as QualifiedNameSyntax)?.Right ??
(node as MemberAccessExpressionSyntax)?.Name;
}
public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget)
{
return (node as QualifiedNameSyntax)?.Left ??
(node as MemberAccessExpressionSyntax)?.Expression;
}
public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier();
public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAssignExpression();
public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression();
public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression();
public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node)
=> (node as AssignmentExpressionSyntax)?.Right;
public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) &&
anonObject.NameEquals == null;
public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostIncrementExpression) ||
node.IsParentKind(SyntaxKind.PreIncrementExpression);
public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostDecrementExpression) ||
node.IsParentKind(SyntaxKind.PreDecrementExpression);
public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node);
public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString)
=> ((InterpolatedStringExpressionSyntax)interpolatedString).Contents;
public bool IsVerbatimStringLiteral(SyntaxToken token)
=> token.IsVerbatimStringLiteral();
public bool IsNumericLiteral(SyntaxToken token)
=> token.Kind() == SyntaxKind.NumericLiteralToken;
public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList)
{
var invocation = (InvocationExpressionSyntax)node;
expression = invocation.Expression;
argumentList = invocation.ArgumentList;
}
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression)
=> GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList);
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression)
=> GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList);
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList)
=> (argumentList as BaseArgumentListSyntax)?.Arguments ?? default;
public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression)
=> ((InvocationExpressionSyntax)invocationExpression).ArgumentList;
public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression)
=> ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList;
public bool IsRegularComment(SyntaxTrivia trivia)
=> trivia.IsRegularComment();
public bool IsDocumentationComment(SyntaxTrivia trivia)
=> trivia.IsDocComment();
public bool IsElastic(SyntaxTrivia trivia)
=> trivia.IsElastic();
public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes)
=> trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes);
public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia)
=> trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia;
public bool IsDocumentationComment(SyntaxNode node)
=> SyntaxFacts.IsDocumentationCommentTrivia(node.Kind());
public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node)
{
return node.IsKind(SyntaxKind.UsingDirective) ||
node.IsKind(SyntaxKind.ExternAliasDirective);
}
public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword);
public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.ModuleKeyword);
private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget)
=> node.IsKind(SyntaxKind.Attribute) &&
node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) &&
attributeList.Target?.Identifier.Kind() == attributeTarget;
private static bool IsMemberDeclaration(SyntaxNode node)
{
// From the C# language spec:
// class-member-declaration:
// constant-declaration
// field-declaration
// method-declaration
// property-declaration
// event-declaration
// indexer-declaration
// operator-declaration
// constructor-declaration
// destructor-declaration
// static-constructor-declaration
// type-declaration
switch (node.Kind())
{
// Because fields declarations can define multiple symbols "public int a, b;"
// We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
case SyntaxKind.VariableDeclarator:
return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) ||
node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
return true;
default:
return false;
}
}
public bool IsDeclaration(SyntaxNode node)
=> SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node);
public bool IsTypeDeclaration(SyntaxNode node)
=> SyntaxFacts.IsTypeDeclaration(node.Kind());
public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node)
=> ((ObjectCreationExpressionSyntax)node).Initializer;
public SyntaxNode GetObjectCreationType(SyntaxNode node)
=> ((ObjectCreationExpressionSyntax)node).Type;
public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement)
=> statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) &&
exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression);
public void GetPartsOfAssignmentStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
GetPartsOfAssignmentExpressionOrStatement(
((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right);
}
public void GetPartsOfAssignmentExpressionOrStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var expression = statement;
if (statement is ExpressionStatementSyntax expressionStatement)
{
expression = expressionStatement.Expression;
}
var assignment = (AssignmentExpressionSyntax)expression;
left = assignment.Left;
operatorToken = assignment.OperatorToken;
right = assignment.Right;
}
public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression)
=> ((MemberAccessExpressionSyntax)memberAccessExpression).Name;
public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name)
{
var memberAccess = (MemberAccessExpressionSyntax)node;
expression = memberAccess.Expression;
operatorToken = memberAccess.OperatorToken;
name = memberAccess.Name;
}
public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node)
=> ((SimpleNameSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node)
=> ((IdentifierNameSyntax)node).Identifier;
public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.LocalFunctionStatement);
public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement)
{
return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains(
(VariableDeclaratorSyntax)declarator);
}
public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2)
=> SyntaxFactory.AreEquivalent(token1, token2);
public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2)
=> SyntaxFactory.AreEquivalent(node1, node2);
public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node?.Parent as InvocationExpressionSyntax)?.Expression == node;
public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node?.Parent as AwaitExpressionSyntax)?.Expression == node;
public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node;
public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node)
=> ((InvocationExpressionSyntax)node).Expression;
public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node)
=> ((AwaitExpressionSyntax)node).Expression;
public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node;
public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node)
=> ((ExpressionStatementSyntax)node).Expression;
public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryExpressionSyntax;
public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsExpression);
public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryExpression = (BinaryExpressionSyntax)node;
left = binaryExpression.Left;
operatorToken = binaryExpression.OperatorToken;
right = binaryExpression.Right;
}
public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse)
{
var conditionalExpression = (ConditionalExpressionSyntax)node;
condition = conditionalExpression.Condition;
whenTrue = conditionalExpression.WhenTrue;
whenFalse = conditionalExpression.WhenFalse;
}
[return: NotNullIfNotNull("node")]
public SyntaxNode? WalkDownParentheses(SyntaxNode? node)
=> (node as ExpressionSyntax)?.WalkDownParentheses() ?? node;
public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode
{
var tupleExpression = (TupleExpressionSyntax)node;
openParen = tupleExpression.OpenParenToken;
arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments;
closeParen = tupleExpression.CloseParenToken;
}
public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node)
=> ((PrefixUnaryExpressionSyntax)node).Operand;
public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node)
=> ((PrefixUnaryExpressionSyntax)node).OperatorToken;
public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement)
=> ((StatementSyntax)statement).GetNextStatement();
public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsSingleLineComment();
public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsMultiLineComment();
public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsSingleLineDocComment();
public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsMultiLineDocComment();
public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia)
=> trivia.IsShebangDirective();
public override bool IsPreprocessorDirective(SyntaxTrivia trivia)
=> SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration)
{
var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position);
typeDeclaration = node;
if (node == null)
return false;
var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier;
if (fullHeader)
lastToken = node.BaseList?.GetLastToken() ?? lastToken;
return IsOnHeader(root, position, node, lastToken);
}
public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration)
{
var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position);
propertyDeclaration = node;
if (propertyDeclaration == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.Identifier);
}
public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter)
{
var node = TryGetAncestorForLocation<ParameterSyntax>(root, position);
parameter = node;
if (parameter == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node);
}
public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method)
{
var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position);
method = node;
if (method == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.ParameterList);
}
public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction)
{
var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position);
localFunction = node;
if (localFunction == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.ParameterList);
}
public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration)
{
var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position);
localDeclaration = node;
if (localDeclaration == null)
{
return false;
}
var initializersExpressions = node!.Declaration.Variables
.Where(v => v.Initializer != null)
.SelectAsArray(initializedV => initializedV.Initializer!.Value);
return IsOnHeader(root, position, node, node, holes: initializersExpressions);
}
public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement)
{
var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position);
ifStatement = node;
if (ifStatement == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.CloseParenToken);
}
public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement)
{
var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position);
whileStatement = node;
if (whileStatement == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.CloseParenToken);
}
public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement)
{
var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position);
foreachStatement = node;
if (foreachStatement == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.CloseParenToken);
}
public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration)
{
var token = root.FindToken(position);
var typeDecl = token.GetAncestor<TypeDeclarationSyntax>();
typeDeclaration = typeDecl;
if (typeDecl == null)
{
return false;
}
RoslynDebug.AssertNotNull(typeDeclaration);
if (position < typeDecl.OpenBraceToken.Span.End ||
position > typeDecl.CloseBraceToken.Span.Start)
{
return false;
}
var line = sourceText.Lines.GetLineFromPosition(position);
if (!line.IsEmptyOrWhitespace())
{
return false;
}
var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position));
if (member == null)
{
// There are no members, or we're after the last member.
return true;
}
else
{
// We're within a member. Make sure we're in the leading whitespace of
// the member.
if (position < member.SpanStart)
{
foreach (var trivia in member.GetLeadingTrivia())
{
if (!trivia.IsWhitespaceOrEndOfLine())
{
return false;
}
if (trivia.FullSpan.Contains(position))
{
return true;
}
}
}
}
return false;
}
protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken)
=> token.ContainsInterleavedDirective(span, cancellationToken);
public SyntaxTokenList GetModifiers(SyntaxNode? node)
=> node.GetModifiers();
public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers)
=> node.WithModifiers(modifiers);
public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is LiteralExpressionSyntax;
public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node)
=> ((LocalDeclarationStatementSyntax)node).Declaration.Variables;
public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Initializer;
public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type;
public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node)
=> ((EqualsValueClauseSyntax?)node)?.Value;
public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block);
public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit);
public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node)
{
return node switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement),
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
}
public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode(node => IsExecutableBlock(node));
public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node)
=> IsExecutableBlock(node) || node.IsEmbeddedStatementOwner();
public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node)
{
if (IsExecutableBlock(node))
return GetExecutableBlockStatements(node);
else if (node.GetEmbeddedStatement() is { } embeddedStatement)
return ImmutableArray.Create<SyntaxNode>(embeddedStatement);
else
return ImmutableArray<SyntaxNode>.Empty;
}
public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression)
{
var cast = (CastExpressionSyntax)node;
type = cast.Type;
expression = cast.Expression;
}
public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member)
{
return member.GetNameToken();
}
return null;
}
public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node)
=> node.GetAttributeLists();
public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) &&
xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName;
public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia)
{
if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia)
{
return documentationCommentTrivia.Content;
}
throw ExceptionUtilities.UnexpectedValue(trivia.Kind());
}
public override bool CanHaveAccessibility(SyntaxNode declaration)
{
switch (declaration.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.VariableDeclarator:
var declarationKind = this.GetDeclarationKind(declaration);
return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event;
case SyntaxKind.ConstructorDeclaration:
// Static constructor can't have accessibility
return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null;
case SyntaxKind.IndexerDeclaration:
return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null;
case SyntaxKind.MethodDeclaration:
var method = (MethodDeclarationSyntax)declaration;
if (method.ExplicitInterfaceSpecifier != null)
{
// explicit interface methods can't have accessibility.
return false;
}
if (method.Modifiers.Any(SyntaxKind.PartialKeyword))
{
// partial methods can't have accessibility modifiers.
return false;
}
return true;
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null;
default:
return false;
}
}
public override Accessibility GetAccessibility(SyntaxNode declaration)
{
if (!CanHaveAccessibility(declaration))
{
return Accessibility.NotApplicable;
}
var modifierTokens = GetModifierTokens(declaration);
GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _);
return accessibility;
}
public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault)
{
accessibility = Accessibility.NotApplicable;
modifiers = DeclarationModifiers.None;
isDefault = false;
foreach (var token in modifierList)
{
accessibility = (token.Kind(), accessibility) switch
{
(SyntaxKind.PublicKeyword, _) => Accessibility.Public,
(SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal,
(SyntaxKind.PrivateKeyword, _) => Accessibility.Private,
(SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal,
(SyntaxKind.InternalKeyword, _) => Accessibility.Internal,
(SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal,
(SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal,
(SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected,
_ => accessibility,
};
modifiers |= token.Kind() switch
{
SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract,
SyntaxKind.NewKeyword => DeclarationModifiers.New,
SyntaxKind.OverrideKeyword => DeclarationModifiers.Override,
SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual,
SyntaxKind.StaticKeyword => DeclarationModifiers.Static,
SyntaxKind.AsyncKeyword => DeclarationModifiers.Async,
SyntaxKind.ConstKeyword => DeclarationModifiers.Const,
SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly,
SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed,
SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe,
SyntaxKind.PartialKeyword => DeclarationModifiers.Partial,
SyntaxKind.RefKeyword => DeclarationModifiers.Ref,
SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile,
SyntaxKind.ExternKeyword => DeclarationModifiers.Extern,
_ => DeclarationModifiers.None,
};
isDefault |= token.Kind() == SyntaxKind.DefaultKeyword;
}
}
public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration)
=> declaration switch
{
MemberDeclarationSyntax memberDecl => memberDecl.Modifiers,
ParameterSyntax parameter => parameter.Modifiers,
LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers,
LocalFunctionStatementSyntax localFunc => localFunc.Modifiers,
AccessorDeclarationSyntax accessor => accessor.Modifiers,
VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent),
VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent),
AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers,
_ => default,
};
public override DeclarationKind GetDeclarationKind(SyntaxNode declaration)
{
switch (declaration.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
return DeclarationKind.Class;
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
return DeclarationKind.Struct;
case SyntaxKind.InterfaceDeclaration:
return DeclarationKind.Interface;
case SyntaxKind.EnumDeclaration:
return DeclarationKind.Enum;
case SyntaxKind.DelegateDeclaration:
return DeclarationKind.Delegate;
case SyntaxKind.MethodDeclaration:
return DeclarationKind.Method;
case SyntaxKind.OperatorDeclaration:
return DeclarationKind.Operator;
case SyntaxKind.ConversionOperatorDeclaration:
return DeclarationKind.ConversionOperator;
case SyntaxKind.ConstructorDeclaration:
return DeclarationKind.Constructor;
case SyntaxKind.DestructorDeclaration:
return DeclarationKind.Destructor;
case SyntaxKind.PropertyDeclaration:
return DeclarationKind.Property;
case SyntaxKind.IndexerDeclaration:
return DeclarationKind.Indexer;
case SyntaxKind.EventDeclaration:
return DeclarationKind.CustomEvent;
case SyntaxKind.EnumMemberDeclaration:
return DeclarationKind.EnumMember;
case SyntaxKind.CompilationUnit:
return DeclarationKind.CompilationUnit;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return DeclarationKind.Namespace;
case SyntaxKind.UsingDirective:
return DeclarationKind.NamespaceImport;
case SyntaxKind.Parameter:
return DeclarationKind.Parameter;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
return DeclarationKind.LambdaExpression;
case SyntaxKind.FieldDeclaration:
var fd = (FieldDeclarationSyntax)declaration;
if (fd.Declaration != null && fd.Declaration.Variables.Count == 1)
{
// this node is considered the declaration if it contains only one variable.
return DeclarationKind.Field;
}
else
{
return DeclarationKind.None;
}
case SyntaxKind.EventFieldDeclaration:
var ef = (EventFieldDeclarationSyntax)declaration;
if (ef.Declaration != null && ef.Declaration.Variables.Count == 1)
{
// this node is considered the declaration if it contains only one variable.
return DeclarationKind.Event;
}
else
{
return DeclarationKind.None;
}
case SyntaxKind.LocalDeclarationStatement:
var ld = (LocalDeclarationStatementSyntax)declaration;
if (ld.Declaration != null && ld.Declaration.Variables.Count == 1)
{
// this node is considered the declaration if it contains only one variable.
return DeclarationKind.Variable;
}
else
{
return DeclarationKind.None;
}
case SyntaxKind.VariableDeclaration:
{
var vd = (VariableDeclarationSyntax)declaration;
if (vd.Variables.Count == 1 && vd.Parent == null)
{
// this node is the declaration if it contains only one variable and has no parent.
return DeclarationKind.Variable;
}
else
{
return DeclarationKind.None;
}
}
case SyntaxKind.VariableDeclarator:
{
var vd = declaration.Parent as VariableDeclarationSyntax;
// this node is considered the declaration if it is one among many, or it has no parent
if (vd == null || vd.Variables.Count > 1)
{
if (ParentIsFieldDeclaration(vd))
{
return DeclarationKind.Field;
}
else if (ParentIsEventFieldDeclaration(vd))
{
return DeclarationKind.Event;
}
else
{
return DeclarationKind.Variable;
}
}
break;
}
case SyntaxKind.AttributeList:
var list = (AttributeListSyntax)declaration;
if (list.Attributes.Count == 1)
{
return DeclarationKind.Attribute;
}
break;
case SyntaxKind.Attribute:
if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1)
{
return DeclarationKind.Attribute;
}
break;
case SyntaxKind.GetAccessorDeclaration:
return DeclarationKind.GetAccessor;
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
return DeclarationKind.SetAccessor;
case SyntaxKind.AddAccessorDeclaration:
return DeclarationKind.AddAccessor;
case SyntaxKind.RemoveAccessorDeclaration:
return DeclarationKind.RemoveAccessor;
}
return DeclarationKind.None;
}
internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false;
internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false;
internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false;
public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsPatternExpression);
public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right)
{
var isPatternExpression = (IsPatternExpressionSyntax)node;
left = isPatternExpression.Expression;
isToken = isPatternExpression.IsKeyword;
right = isPatternExpression.Pattern;
}
public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is PatternSyntax;
public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ConstantPattern);
public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.DeclarationPattern);
public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.RecursivePattern);
public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.VarPattern);
public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node)
=> ((ConstantPatternSyntax)node).Expression;
public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation)
{
var declarationPattern = (DeclarationPatternSyntax)node;
type = declarationPattern.Type;
designation = declarationPattern.Designation;
}
public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation)
{
var recursivePattern = (RecursivePatternSyntax)node;
type = recursivePattern.Type;
positionalPart = recursivePattern.PositionalPatternClause;
propertyPart = recursivePattern.PropertyPatternClause;
designation = recursivePattern.Designation;
}
public bool SupportsNotPattern(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove();
public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AndPattern);
public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryPatternSyntax;
public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.NotPattern);
public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.OrPattern);
public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParenthesizedPattern);
public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.TypePattern);
public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is UnaryPatternSyntax;
public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen)
{
var parenthesizedPattern = (ParenthesizedPatternSyntax)node;
openParen = parenthesizedPattern.OpenParenToken;
pattern = parenthesizedPattern.Pattern;
closeParen = parenthesizedPattern.CloseParenToken;
}
public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryPattern = (BinaryPatternSyntax)node;
left = binaryPattern.Left;
operatorToken = binaryPattern.OperatorToken;
right = binaryPattern.Right;
}
public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern)
{
var unaryPattern = (UnaryPatternSyntax)node;
operatorToken = unaryPattern.OperatorToken;
pattern = unaryPattern.Pattern;
}
public SyntaxNode GetTypeOfTypePattern(SyntaxNode node)
=> ((TypePatternSyntax)node).Type;
public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ImplicitObjectCreationExpression);
public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression)
=> ((ThrowExpressionSyntax)throwExpression).Expression;
public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ThrowStatement);
public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.LocalFunctionStatement);
public void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken)
{
var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node;
stringStartToken = interpolatedStringExpression.StringStartToken;
contents = interpolatedStringExpression.Contents;
stringEndToken = interpolatedStringExpression.StringEndToken;
}
public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node)
=> node is InterpolatedStringExpressionSyntax interpolatedString &&
interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.CSharp.LanguageServices
{
internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts
{
internal static readonly CSharpSyntaxFacts Instance = new();
protected CSharpSyntaxFacts()
{
}
public bool IsCaseSensitive => true;
public StringComparer StringComparer { get; } = StringComparer.Ordinal;
public SyntaxTrivia ElasticMarker
=> SyntaxFactory.ElasticMarker;
public SyntaxTrivia ElasticCarriageReturnLineFeed
=> SyntaxFactory.ElasticCarriageReturnLineFeed;
public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance;
protected override IDocumentationCommentService DocumentationCommentService
=> CSharpDocumentationCommentService.Instance;
public bool SupportsIndexingInitializer(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6;
public bool SupportsThrowExpression(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsLocalFunctionDeclaration(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsRecord(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9;
public bool SupportsRecordStruct(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove();
public SyntaxToken ParseToken(string text)
=> SyntaxFactory.ParseToken(text);
public SyntaxTriviaList ParseLeadingTrivia(string text)
=> SyntaxFactory.ParseLeadingTrivia(text);
public string EscapeIdentifier(string identifier)
{
var nullIndex = identifier.IndexOf('\0');
if (nullIndex >= 0)
{
identifier = identifier.Substring(0, nullIndex);
}
var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
return needsEscaping ? "@" + identifier : identifier;
}
public bool IsVerbatimIdentifier(SyntaxToken token)
=> token.IsVerbatimIdentifier();
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsReservedKeyword(SyntaxToken token)
=> SyntaxFacts.IsReservedKeyword(token.Kind());
public bool IsContextualKeyword(SyntaxToken token)
=> SyntaxFacts.IsContextualKeyword(token.Kind());
public bool IsPreprocessorKeyword(SyntaxToken token)
=> SyntaxFacts.IsPreprocessorKeyword(token.Kind());
public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
=> syntaxTree.IsPreProcessorDirectiveContext(
position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree == null)
{
return false;
}
return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is DirectiveTriviaSyntax;
public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info)
{
if (node is LineDirectiveTriviaSyntax lineDirective)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default;
return false;
}
public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsRightSideOfQualifiedName();
}
public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsSimpleMemberAccessExpressionName();
}
public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node;
public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberBindingExpressionName();
}
[return: NotNullIfNotNull("node")]
public SyntaxNode? GetStandaloneExpression(SyntaxNode? node)
=> node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node;
public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node)
=> node.GetRootConditionalAccessExpression();
public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) &&
objectCreation.Type == node;
public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is DeclarationExpressionSyntax;
public bool IsAttributeName(SyntaxNode node)
=> SyntaxFacts.IsAttributeName(node);
public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node)
{
return node is ParenthesizedLambdaExpressionSyntax ||
node is SimpleLambdaExpressionSyntax ||
node is AnonymousMethodExpressionSyntax;
}
public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node is ArgumentSyntax arg && arg.NameColon != null;
public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.CheckParent<NameColonSyntax>(p => p.Name == node);
public SyntaxToken? GetNameOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Identifier;
public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Default;
public SyntaxNode? GetParameterList(SyntaxNode node)
=> node.GetParameterList();
public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList);
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName)
{
return genericName is GenericNameSyntax csharpGenericName
? csharpGenericName.Identifier
: default;
}
public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) &&
usingDirective.Name == node;
public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null;
public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is ForEachVariableStatementSyntax;
public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node)
=> node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction();
public Location GetDeconstructionReferenceLocation(SyntaxNode node)
{
return node switch
{
AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(),
ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(),
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
}
public bool IsStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node)
{
if (node is BlockSyntax ||
node is ArrowExpressionClauseSyntax)
{
return node.Parent is BaseMethodDeclarationSyntax ||
node.Parent is AccessorDeclarationSyntax;
}
return false;
}
public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node)
=> (node as ReturnStatementSyntax)?.Expression;
public bool IsThisConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsBaseConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsQueryKeyword(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.FromKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.InKeyword:
return token.Parent is QueryClauseSyntax;
case SyntaxKind.ByKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.SelectKeyword:
return token.Parent is SelectOrGroupClauseSyntax;
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return token.Parent is OrderingSyntax;
case SyntaxKind.IntoKeyword:
return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation);
default:
return false;
}
}
public bool IsThrowExpression(SyntaxNode node)
=> node.Kind() == SyntaxKind.ThrowExpression;
public bool IsPredefinedType(SyntaxToken token)
=> TryGetPredefinedType(token, out _);
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
=> TryGetPredefinedType(token, out var actualType) && actualType == type;
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private static PredefinedType GetPredefinedType(SyntaxToken token)
{
return (SyntaxKind)token.RawKind switch
{
SyntaxKind.BoolKeyword => PredefinedType.Boolean,
SyntaxKind.ByteKeyword => PredefinedType.Byte,
SyntaxKind.SByteKeyword => PredefinedType.SByte,
SyntaxKind.IntKeyword => PredefinedType.Int32,
SyntaxKind.UIntKeyword => PredefinedType.UInt32,
SyntaxKind.ShortKeyword => PredefinedType.Int16,
SyntaxKind.UShortKeyword => PredefinedType.UInt16,
SyntaxKind.LongKeyword => PredefinedType.Int64,
SyntaxKind.ULongKeyword => PredefinedType.UInt64,
SyntaxKind.FloatKeyword => PredefinedType.Single,
SyntaxKind.DoubleKeyword => PredefinedType.Double,
SyntaxKind.DecimalKeyword => PredefinedType.Decimal,
SyntaxKind.StringKeyword => PredefinedType.String,
SyntaxKind.CharKeyword => PredefinedType.Char,
SyntaxKind.ObjectKeyword => PredefinedType.Object,
SyntaxKind.VoidKeyword => PredefinedType.Void,
_ => PredefinedType.None,
};
}
public bool IsPredefinedOperator(SyntaxToken token)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None;
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op;
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private static PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanToken:
return PredefinedOperator.LessThan;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
=> SyntaxFacts.GetText((SyntaxKind)kind);
public bool IsIdentifierStartCharacter(char c)
=> SyntaxFacts.IsIdentifierStartCharacter(c);
public bool IsIdentifierPartCharacter(char c)
=> SyntaxFacts.IsIdentifierPartCharacter(c);
public bool IsIdentifierEscapeCharacter(char c)
=> c == '@';
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c) => false;
public bool IsStartOfUnicodeEscapeSequence(char c)
=> c == '\\';
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
return true;
default:
return false;
}
}
public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token)
=> token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.IsKind(SyntaxKind.NumericLiteralExpression) == true;
public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent)
{
var typedToken = token;
var typedParent = parent;
if (typedParent.IsKind(SyntaxKind.IdentifierName))
{
TypeSyntax? declaredType = null;
if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl))
{
declaredType = varDecl.Type;
}
else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl))
{
declaredType = fieldDecl.Declaration.Type;
}
return declaredType == typedParent && typedToken.ValueText == "var";
}
return false;
}
public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent)
{
if (parent is ExpressionSyntax typedParent)
{
if (SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
typedParent.IsKind(SyntaxKind.IdentifierName) &&
token.ValueText == "dynamic")
{
return true;
}
}
return false;
}
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
// In the order by clause a comma might be bound to ThenBy or ThenByDescending
if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause))
{
return true;
}
return false;
}
public void GetPartsOfConditionalAccessExpression(
SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull)
{
var conditionalAccess = (ConditionalAccessExpressionSyntax)node;
expression = conditionalAccess.Expression;
operatorToken = conditionalAccess.OperatorToken;
whenNotNull = conditionalAccess.WhenNotNull;
}
public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is PostfixUnaryExpressionSyntax;
public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberBindingExpressionSyntax;
public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression;
public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity)
{
name = null;
arity = 0;
if (node is SimpleNameSyntax simpleName)
{
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
}
public bool LooksGeneric(SyntaxNode simpleName)
=> simpleName.IsKind(SyntaxKind.GenericName) ||
simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken;
public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node)
=> (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression;
public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node)
=> ((MemberBindingExpressionSyntax)node).Name;
public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget)
=> (node as MemberAccessExpressionSyntax)?.Expression;
public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList)
{
var elementAccess = node as ElementAccessExpressionSyntax;
expression = elementAccess?.Expression;
argumentList = elementAccess?.ArgumentList;
}
public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node)
=> (node as InterpolationSyntax)?.Expression;
public bool IsInStaticContext(SyntaxNode node)
=> node.IsInStaticContext();
public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.BaseList);
public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node)
=> (node as ArgumentSyntax)?.Expression;
public RefKind GetRefKindOfArgument(SyntaxNode? node)
=> (node as ArgumentSyntax).GetRefKind();
public bool IsArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Argument);
public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node)
{
return node is ArgumentSyntax argument &&
argument.RefOrOutKeyword.Kind() == SyntaxKind.None &&
argument.NameColon == null;
}
public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsInConstantContext();
public bool IsInConstructor(SyntaxNode node)
=> node.GetAncestor<ConstructorDeclarationSyntax>() != null;
public bool IsUnsafeContext(SyntaxNode node)
=> node.IsUnsafeContext();
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
=> ((AttributeSyntax)node).Name;
public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node)
=> ((ParenthesizedExpressionSyntax)node).Expression;
public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier();
public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node)
=> throw ExceptionUtilities.Unreachable;
public SyntaxToken FindTokenOnLeftOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public SyntaxToken FindTokenOnRightOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IdentifierName) &&
node.IsParentKind(SyntaxKind.NameColon) &&
node.Parent.IsParentKind(SyntaxKind.Subpattern);
public bool IsPropertyPatternClause(SyntaxNode node)
=> node.Kind() == SyntaxKind.PropertyPatternClause;
public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> IsMemberInitializerNamedAssignmentIdentifier(node, out _);
public bool IsMemberInitializerNamedAssignmentIdentifier(
[NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance)
{
initializedInstance = null;
if (node is IdentifierNameSyntax identifier &&
identifier.IsLeftSideOfAssignExpression())
{
if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression))
{
var withInitializer = identifier.Parent.GetRequiredParent();
initializedInstance = withInitializer.GetRequiredParent();
return true;
}
else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression))
{
var objectInitializer = identifier.Parent.GetRequiredParent();
if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax)
{
initializedInstance = objectInitializer.Parent;
return true;
}
else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment))
{
initializedInstance = assignment.Left;
return true;
}
}
}
return false;
}
public bool IsElementAccessExpression(SyntaxNode? node)
=> node.IsKind(SyntaxKind.ElementAccessExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false)
=> node.ConvertToSingleLine(useElasticTrivia);
public void GetPartsOfParenthesizedExpression(
SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen)
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)node;
openParen = parenthesizedExpression.OpenParenToken;
expression = parenthesizedExpression.Expression;
closeParen = parenthesizedExpression.CloseParenToken;
}
public bool IsIndexerMemberCRef(SyntaxNode? node)
=> node.IsKind(SyntaxKind.IndexerMemberCref);
public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
var kind = node.Kind();
if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax ||
node is EnumMemberDeclarationSyntax ||
node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseNamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
private const string dotToken = ".";
public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string?>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent is BaseNamespaceDeclarationSyntax)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string? GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.IncompleteMember:
return missingTokenPlaceholder;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string? name = null;
if (node is MemberDeclarationSyntax memberDeclaration)
{
if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration)
{
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
else
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember);
name = "?";
}
}
}
else
{
if (node is VariableDeclaratorSyntax fieldDeclarator)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (var i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: true, methodLevel: true);
return list;
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: false, methodLevel: true);
return list;
}
public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node?.Kind() == SyntaxKind.ClassDeclaration;
public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node is BaseNamespaceDeclarationSyntax;
public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node)
=> (node as BaseNamespaceDeclarationSyntax)?.Name;
public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration)
=> ((TypeDeclarationSyntax)typeDeclaration).Members;
public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration)
=> ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members;
public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit)
=> ((CompilationUnitSyntax)compilationUnit).Members;
public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration)
=> ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings;
public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit)
=> ((CompilationUnitSyntax)compilationUnit).Usings;
private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel)
{
Debug.Assert(topLevel || methodLevel);
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (topLevel)
{
list.Add(member);
}
AppendMembers(member, list, topLevel, methodLevel);
continue;
}
if (methodLevel && IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default;
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default;
}
// TODO: currently we only support method for now
if (member is BaseMethodDeclarationSyntax method)
{
if (method.Body == null)
{
return default;
}
return GetBlockBodySpan(method.Body);
}
return default;
}
public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span)
{
switch (node)
{
case ConstructorDeclarationSyntax constructor:
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
case BaseMethodDeclarationSyntax method:
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
case BasePropertyDeclarationSyntax property:
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
case EnumMemberDeclarationSyntax @enum:
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
case BaseFieldDeclarationSyntax field:
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private static TextSpan GetBlockBodySpan(BlockSyntax body)
=> TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
public SyntaxNode? TryGetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
if (parent is MemberAccessExpressionSyntax memberAccess)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is QualifiedNameSyntax qualifiedName)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
if (parent is ObjectCreationExpressionSyntax objectCreation)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
if (!(parent is NameSyntax))
{
break;
}
node = parent;
}
if (node is VarPatternSyntax)
{
return node;
}
// Patterns are never bindable (though their constituent types/exprs may be).
return node is PatternSyntax ? null : node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken)
{
if (!(root is CompilationUnitSyntax compilationUnit))
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
switch (member)
{
case ConstructorDeclarationSyntax constructor:
constructors.Add(constructor);
continue;
case BaseNamespaceDeclarationSyntax @namespace:
AppendConstructors(@namespace.Members, constructors, cancellationToken);
break;
case ClassDeclarationSyntax @class:
AppendConstructors(@class.Members, constructors, cancellationToken);
break;
case RecordDeclarationSyntax record:
AppendConstructors(record.Members, constructors, cancellationToken);
break;
case StructDeclarationSyntax @struct:
AppendConstructors(@struct.Members, constructors, cancellationToken);
break;
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.openBrace;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default;
return false;
}
public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return trivia.FullSpan;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return default;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return default;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax branch)
{
return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default;
}
}
}
}
return default;
}
public string GetNameForArgument(SyntaxNode? argument)
=> (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty;
public string GetNameForAttributeArgument(SyntaxNode? argument)
=> (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty;
public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfDot();
public SyntaxNode? GetRightSideOfDot(SyntaxNode? node)
{
return (node as QualifiedNameSyntax)?.Right ??
(node as MemberAccessExpressionSyntax)?.Name;
}
public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget)
{
return (node as QualifiedNameSyntax)?.Left ??
(node as MemberAccessExpressionSyntax)?.Expression;
}
public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier();
public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAssignExpression();
public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression();
public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression();
public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node)
=> (node as AssignmentExpressionSyntax)?.Right;
public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) &&
anonObject.NameEquals == null;
public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostIncrementExpression) ||
node.IsParentKind(SyntaxKind.PreIncrementExpression);
public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostDecrementExpression) ||
node.IsParentKind(SyntaxKind.PreDecrementExpression);
public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node);
public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString)
=> ((InterpolatedStringExpressionSyntax)interpolatedString).Contents;
public bool IsVerbatimStringLiteral(SyntaxToken token)
=> token.IsVerbatimStringLiteral();
public bool IsNumericLiteral(SyntaxToken token)
=> token.Kind() == SyntaxKind.NumericLiteralToken;
public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList)
{
var invocation = (InvocationExpressionSyntax)node;
expression = invocation.Expression;
argumentList = invocation.ArgumentList;
}
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression)
=> GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList);
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression)
=> GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList);
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList)
=> (argumentList as BaseArgumentListSyntax)?.Arguments ?? default;
public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression)
=> ((InvocationExpressionSyntax)invocationExpression).ArgumentList;
public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression)
=> ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList;
public bool IsRegularComment(SyntaxTrivia trivia)
=> trivia.IsRegularComment();
public bool IsDocumentationComment(SyntaxTrivia trivia)
=> trivia.IsDocComment();
public bool IsElastic(SyntaxTrivia trivia)
=> trivia.IsElastic();
public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes)
=> trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes);
public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia)
=> trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia;
public bool IsDocumentationComment(SyntaxNode node)
=> SyntaxFacts.IsDocumentationCommentTrivia(node.Kind());
public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node)
{
return node.IsKind(SyntaxKind.UsingDirective) ||
node.IsKind(SyntaxKind.ExternAliasDirective);
}
public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword);
public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.ModuleKeyword);
private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget)
=> node.IsKind(SyntaxKind.Attribute) &&
node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) &&
attributeList.Target?.Identifier.Kind() == attributeTarget;
private static bool IsMemberDeclaration(SyntaxNode node)
{
// From the C# language spec:
// class-member-declaration:
// constant-declaration
// field-declaration
// method-declaration
// property-declaration
// event-declaration
// indexer-declaration
// operator-declaration
// constructor-declaration
// destructor-declaration
// static-constructor-declaration
// type-declaration
switch (node.Kind())
{
// Because fields declarations can define multiple symbols "public int a, b;"
// We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
case SyntaxKind.VariableDeclarator:
return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) ||
node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
return true;
default:
return false;
}
}
public bool IsDeclaration(SyntaxNode node)
=> SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node);
public bool IsTypeDeclaration(SyntaxNode node)
=> SyntaxFacts.IsTypeDeclaration(node.Kind());
public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node)
=> ((ObjectCreationExpressionSyntax)node).Initializer;
public SyntaxNode GetObjectCreationType(SyntaxNode node)
=> ((ObjectCreationExpressionSyntax)node).Type;
public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement)
=> statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) &&
exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression);
public void GetPartsOfAssignmentStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
GetPartsOfAssignmentExpressionOrStatement(
((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right);
}
public void GetPartsOfAssignmentExpressionOrStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var expression = statement;
if (statement is ExpressionStatementSyntax expressionStatement)
{
expression = expressionStatement.Expression;
}
var assignment = (AssignmentExpressionSyntax)expression;
left = assignment.Left;
operatorToken = assignment.OperatorToken;
right = assignment.Right;
}
public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression)
=> ((MemberAccessExpressionSyntax)memberAccessExpression).Name;
public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name)
{
var memberAccess = (MemberAccessExpressionSyntax)node;
expression = memberAccess.Expression;
operatorToken = memberAccess.OperatorToken;
name = memberAccess.Name;
}
public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node)
=> ((SimpleNameSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node)
=> ((IdentifierNameSyntax)node).Identifier;
public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.LocalFunctionStatement);
public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement)
{
return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains(
(VariableDeclaratorSyntax)declarator);
}
public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2)
=> SyntaxFactory.AreEquivalent(token1, token2);
public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2)
=> SyntaxFactory.AreEquivalent(node1, node2);
public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node?.Parent as InvocationExpressionSyntax)?.Expression == node;
public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node?.Parent as AwaitExpressionSyntax)?.Expression == node;
public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node;
public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node)
=> ((InvocationExpressionSyntax)node).Expression;
public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node)
=> ((AwaitExpressionSyntax)node).Expression;
public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node;
public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node)
=> ((ExpressionStatementSyntax)node).Expression;
public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryExpressionSyntax;
public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsExpression);
public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryExpression = (BinaryExpressionSyntax)node;
left = binaryExpression.Left;
operatorToken = binaryExpression.OperatorToken;
right = binaryExpression.Right;
}
public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse)
{
var conditionalExpression = (ConditionalExpressionSyntax)node;
condition = conditionalExpression.Condition;
whenTrue = conditionalExpression.WhenTrue;
whenFalse = conditionalExpression.WhenFalse;
}
[return: NotNullIfNotNull("node")]
public SyntaxNode? WalkDownParentheses(SyntaxNode? node)
=> (node as ExpressionSyntax)?.WalkDownParentheses() ?? node;
public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode
{
var tupleExpression = (TupleExpressionSyntax)node;
openParen = tupleExpression.OpenParenToken;
arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments;
closeParen = tupleExpression.CloseParenToken;
}
public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node)
=> ((PrefixUnaryExpressionSyntax)node).Operand;
public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node)
=> ((PrefixUnaryExpressionSyntax)node).OperatorToken;
public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement)
=> ((StatementSyntax)statement).GetNextStatement();
public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsSingleLineComment();
public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsMultiLineComment();
public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsSingleLineDocComment();
public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia)
=> trivia.IsMultiLineDocComment();
public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia)
=> trivia.IsShebangDirective();
public override bool IsPreprocessorDirective(SyntaxTrivia trivia)
=> SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration)
{
var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position);
typeDeclaration = node;
if (node == null)
return false;
var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier;
if (fullHeader)
lastToken = node.BaseList?.GetLastToken() ?? lastToken;
return IsOnHeader(root, position, node, lastToken);
}
public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration)
{
var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position);
propertyDeclaration = node;
if (propertyDeclaration == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.Identifier);
}
public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter)
{
var node = TryGetAncestorForLocation<ParameterSyntax>(root, position);
parameter = node;
if (parameter == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node);
}
public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method)
{
var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position);
method = node;
if (method == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.ParameterList);
}
public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction)
{
var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position);
localFunction = node;
if (localFunction == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.ParameterList);
}
public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration)
{
var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position);
localDeclaration = node;
if (localDeclaration == null)
{
return false;
}
var initializersExpressions = node!.Declaration.Variables
.Where(v => v.Initializer != null)
.SelectAsArray(initializedV => initializedV.Initializer!.Value);
return IsOnHeader(root, position, node, node, holes: initializersExpressions);
}
public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement)
{
var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position);
ifStatement = node;
if (ifStatement == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.CloseParenToken);
}
public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement)
{
var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position);
whileStatement = node;
if (whileStatement == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.CloseParenToken);
}
public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement)
{
var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position);
foreachStatement = node;
if (foreachStatement == null)
{
return false;
}
RoslynDebug.AssertNotNull(node);
return IsOnHeader(root, position, node, node.CloseParenToken);
}
public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration)
{
var token = root.FindToken(position);
var typeDecl = token.GetAncestor<TypeDeclarationSyntax>();
typeDeclaration = typeDecl;
if (typeDecl == null)
{
return false;
}
RoslynDebug.AssertNotNull(typeDeclaration);
if (position < typeDecl.OpenBraceToken.Span.End ||
position > typeDecl.CloseBraceToken.Span.Start)
{
return false;
}
var line = sourceText.Lines.GetLineFromPosition(position);
if (!line.IsEmptyOrWhitespace())
{
return false;
}
var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position));
if (member == null)
{
// There are no members, or we're after the last member.
return true;
}
else
{
// We're within a member. Make sure we're in the leading whitespace of
// the member.
if (position < member.SpanStart)
{
foreach (var trivia in member.GetLeadingTrivia())
{
if (!trivia.IsWhitespaceOrEndOfLine())
{
return false;
}
if (trivia.FullSpan.Contains(position))
{
return true;
}
}
}
}
return false;
}
protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken)
=> token.ContainsInterleavedDirective(span, cancellationToken);
public SyntaxTokenList GetModifiers(SyntaxNode? node)
=> node.GetModifiers();
public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers)
=> node.WithModifiers(modifiers);
public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is LiteralExpressionSyntax;
public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node)
=> ((LocalDeclarationStatementSyntax)node).Declaration.Variables;
public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Initializer;
public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type;
public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node)
=> ((EqualsValueClauseSyntax?)node)?.Value;
public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block);
public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit);
public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node)
{
return node switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement),
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
}
public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode(node => IsExecutableBlock(node));
public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node)
=> IsExecutableBlock(node) || node.IsEmbeddedStatementOwner();
public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node)
{
if (IsExecutableBlock(node))
return GetExecutableBlockStatements(node);
else if (node.GetEmbeddedStatement() is { } embeddedStatement)
return ImmutableArray.Create<SyntaxNode>(embeddedStatement);
else
return ImmutableArray<SyntaxNode>.Empty;
}
public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression)
{
var cast = (CastExpressionSyntax)node;
type = cast.Type;
expression = cast.Expression;
}
public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member)
{
return member.GetNameToken();
}
return null;
}
public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node)
=> node.GetAttributeLists();
public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) &&
xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName;
public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia)
{
if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia)
{
return documentationCommentTrivia.Content;
}
throw ExceptionUtilities.UnexpectedValue(trivia.Kind());
}
public override bool CanHaveAccessibility(SyntaxNode declaration)
{
switch (declaration.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.VariableDeclarator:
var declarationKind = this.GetDeclarationKind(declaration);
return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event;
case SyntaxKind.ConstructorDeclaration:
// Static constructor can't have accessibility
return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null;
case SyntaxKind.IndexerDeclaration:
return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null;
case SyntaxKind.MethodDeclaration:
var method = (MethodDeclarationSyntax)declaration;
if (method.ExplicitInterfaceSpecifier != null)
{
// explicit interface methods can't have accessibility.
return false;
}
if (method.Modifiers.Any(SyntaxKind.PartialKeyword))
{
// partial methods can't have accessibility modifiers.
return false;
}
return true;
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null;
default:
return false;
}
}
public override Accessibility GetAccessibility(SyntaxNode declaration)
{
if (!CanHaveAccessibility(declaration))
{
return Accessibility.NotApplicable;
}
var modifierTokens = GetModifierTokens(declaration);
GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _);
return accessibility;
}
public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault)
{
accessibility = Accessibility.NotApplicable;
modifiers = DeclarationModifiers.None;
isDefault = false;
foreach (var token in modifierList)
{
accessibility = (token.Kind(), accessibility) switch
{
(SyntaxKind.PublicKeyword, _) => Accessibility.Public,
(SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal,
(SyntaxKind.PrivateKeyword, _) => Accessibility.Private,
(SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal,
(SyntaxKind.InternalKeyword, _) => Accessibility.Internal,
(SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal,
(SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal,
(SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected,
_ => accessibility,
};
modifiers |= token.Kind() switch
{
SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract,
SyntaxKind.NewKeyword => DeclarationModifiers.New,
SyntaxKind.OverrideKeyword => DeclarationModifiers.Override,
SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual,
SyntaxKind.StaticKeyword => DeclarationModifiers.Static,
SyntaxKind.AsyncKeyword => DeclarationModifiers.Async,
SyntaxKind.ConstKeyword => DeclarationModifiers.Const,
SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly,
SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed,
SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe,
SyntaxKind.PartialKeyword => DeclarationModifiers.Partial,
SyntaxKind.RefKeyword => DeclarationModifiers.Ref,
SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile,
SyntaxKind.ExternKeyword => DeclarationModifiers.Extern,
_ => DeclarationModifiers.None,
};
isDefault |= token.Kind() == SyntaxKind.DefaultKeyword;
}
}
public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration)
=> declaration switch
{
MemberDeclarationSyntax memberDecl => memberDecl.Modifiers,
ParameterSyntax parameter => parameter.Modifiers,
LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers,
LocalFunctionStatementSyntax localFunc => localFunc.Modifiers,
AccessorDeclarationSyntax accessor => accessor.Modifiers,
VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent),
VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent),
AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers,
_ => default,
};
public override DeclarationKind GetDeclarationKind(SyntaxNode declaration)
{
switch (declaration.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
return DeclarationKind.Class;
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
return DeclarationKind.Struct;
case SyntaxKind.InterfaceDeclaration:
return DeclarationKind.Interface;
case SyntaxKind.EnumDeclaration:
return DeclarationKind.Enum;
case SyntaxKind.DelegateDeclaration:
return DeclarationKind.Delegate;
case SyntaxKind.MethodDeclaration:
return DeclarationKind.Method;
case SyntaxKind.OperatorDeclaration:
return DeclarationKind.Operator;
case SyntaxKind.ConversionOperatorDeclaration:
return DeclarationKind.ConversionOperator;
case SyntaxKind.ConstructorDeclaration:
return DeclarationKind.Constructor;
case SyntaxKind.DestructorDeclaration:
return DeclarationKind.Destructor;
case SyntaxKind.PropertyDeclaration:
return DeclarationKind.Property;
case SyntaxKind.IndexerDeclaration:
return DeclarationKind.Indexer;
case SyntaxKind.EventDeclaration:
return DeclarationKind.CustomEvent;
case SyntaxKind.EnumMemberDeclaration:
return DeclarationKind.EnumMember;
case SyntaxKind.CompilationUnit:
return DeclarationKind.CompilationUnit;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return DeclarationKind.Namespace;
case SyntaxKind.UsingDirective:
return DeclarationKind.NamespaceImport;
case SyntaxKind.Parameter:
return DeclarationKind.Parameter;
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
return DeclarationKind.LambdaExpression;
case SyntaxKind.FieldDeclaration:
var fd = (FieldDeclarationSyntax)declaration;
if (fd.Declaration != null && fd.Declaration.Variables.Count == 1)
{
// this node is considered the declaration if it contains only one variable.
return DeclarationKind.Field;
}
else
{
return DeclarationKind.None;
}
case SyntaxKind.EventFieldDeclaration:
var ef = (EventFieldDeclarationSyntax)declaration;
if (ef.Declaration != null && ef.Declaration.Variables.Count == 1)
{
// this node is considered the declaration if it contains only one variable.
return DeclarationKind.Event;
}
else
{
return DeclarationKind.None;
}
case SyntaxKind.LocalDeclarationStatement:
var ld = (LocalDeclarationStatementSyntax)declaration;
if (ld.Declaration != null && ld.Declaration.Variables.Count == 1)
{
// this node is considered the declaration if it contains only one variable.
return DeclarationKind.Variable;
}
else
{
return DeclarationKind.None;
}
case SyntaxKind.VariableDeclaration:
{
var vd = (VariableDeclarationSyntax)declaration;
if (vd.Variables.Count == 1 && vd.Parent == null)
{
// this node is the declaration if it contains only one variable and has no parent.
return DeclarationKind.Variable;
}
else
{
return DeclarationKind.None;
}
}
case SyntaxKind.VariableDeclarator:
{
var vd = declaration.Parent as VariableDeclarationSyntax;
// this node is considered the declaration if it is one among many, or it has no parent
if (vd == null || vd.Variables.Count > 1)
{
if (ParentIsFieldDeclaration(vd))
{
return DeclarationKind.Field;
}
else if (ParentIsEventFieldDeclaration(vd))
{
return DeclarationKind.Event;
}
else
{
return DeclarationKind.Variable;
}
}
break;
}
case SyntaxKind.AttributeList:
var list = (AttributeListSyntax)declaration;
if (list.Attributes.Count == 1)
{
return DeclarationKind.Attribute;
}
break;
case SyntaxKind.Attribute:
if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1)
{
return DeclarationKind.Attribute;
}
break;
case SyntaxKind.GetAccessorDeclaration:
return DeclarationKind.GetAccessor;
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
return DeclarationKind.SetAccessor;
case SyntaxKind.AddAccessorDeclaration:
return DeclarationKind.AddAccessor;
case SyntaxKind.RemoveAccessorDeclaration:
return DeclarationKind.RemoveAccessor;
}
return DeclarationKind.None;
}
internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false;
internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false;
internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false;
public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsPatternExpression);
public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right)
{
var isPatternExpression = (IsPatternExpressionSyntax)node;
left = isPatternExpression.Expression;
isToken = isPatternExpression.IsKeyword;
right = isPatternExpression.Pattern;
}
public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is PatternSyntax;
public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ConstantPattern);
public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.DeclarationPattern);
public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.RecursivePattern);
public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.VarPattern);
public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node)
=> ((ConstantPatternSyntax)node).Expression;
public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation)
{
var declarationPattern = (DeclarationPatternSyntax)node;
type = declarationPattern.Type;
designation = declarationPattern.Designation;
}
public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation)
{
var recursivePattern = (RecursivePatternSyntax)node;
type = recursivePattern.Type;
positionalPart = recursivePattern.PositionalPatternClause;
propertyPart = recursivePattern.PropertyPatternClause;
designation = recursivePattern.Designation;
}
public bool SupportsNotPattern(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove();
public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AndPattern);
public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryPatternSyntax;
public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.NotPattern);
public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.OrPattern);
public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParenthesizedPattern);
public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.TypePattern);
public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is UnaryPatternSyntax;
public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen)
{
var parenthesizedPattern = (ParenthesizedPatternSyntax)node;
openParen = parenthesizedPattern.OpenParenToken;
pattern = parenthesizedPattern.Pattern;
closeParen = parenthesizedPattern.CloseParenToken;
}
public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryPattern = (BinaryPatternSyntax)node;
left = binaryPattern.Left;
operatorToken = binaryPattern.OperatorToken;
right = binaryPattern.Right;
}
public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern)
{
var unaryPattern = (UnaryPatternSyntax)node;
operatorToken = unaryPattern.OperatorToken;
pattern = unaryPattern.Pattern;
}
public SyntaxNode GetTypeOfTypePattern(SyntaxNode node)
=> ((TypePatternSyntax)node).Type;
public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ImplicitObjectCreationExpression);
public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression)
=> ((ThrowExpressionSyntax)throwExpression).Expression;
public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ThrowStatement);
public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.LocalFunctionStatement);
public void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken)
{
var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node;
stringStartToken = interpolatedStringExpression.StringStartToken;
contents = interpolatedStringExpression.Contents;
stringEndToken = interpolatedStringExpression.StringEndToken;
}
public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node)
=> node is InterpolatedStringExpressionSyntax interpolatedString &&
interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
}
}
| 1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/CodeModel/Collections/OverloadsCollection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public sealed class OverloadsCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
CodeFunction parent)
{
var collection = new OverloadsCollection(state, parent);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private OverloadsCollection(
CodeModelState state,
CodeFunction parent)
: base(state, parent)
{
}
private ImmutableArray<EnvDTE.CodeElement> _overloads;
private CodeFunction ParentElement => (CodeFunction)this.Parent;
private ImmutableArray<EnvDTE.CodeElement> GetOverloads()
{
// Retrieving the overloads is potentially very expensive because it can force multiple FileCodeModels to be instantiated.
// Here, we cache the result to avoid having to perform these calculations each time GetOverloads() is called.
// This *could* be an issue because it means that an OverloadsCollection will not necessarily reflect the
// current state of the user's code. However, because a new OverloadsCollection is created every time the Overloads
// property is accessed on CodeFunction, consumers would hit this behavior rarely.
if (_overloads == null)
{
var symbol = (IMethodSymbol)ParentElement.LookupSymbol();
// Only methods and constructors can be overloaded. However, all functions
// can successfully return a collection of overloaded functions; if not
// really overloaded, the collection contains just the original function.
if (symbol.MethodKind != MethodKind.Ordinary &&
symbol.MethodKind != MethodKind.Constructor)
{
return ImmutableArray.Create((EnvDTE.CodeElement)Parent);
}
var solution = this.Workspace.CurrentSolution;
var overloadsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance();
foreach (var method in symbol.ContainingType.GetMembers(symbol.Name))
{
if (method.Kind != SymbolKind.Method)
{
continue;
}
var location = method.Locations.FirstOrDefault(l => l.IsInSource);
if (location != null)
{
var document = solution.GetDocument(location.SourceTree);
if (document != null)
{
var fileCodeModelObject = this.Workspace.GetFileCodeModel(document.Id);
if (fileCodeModelObject != null)
{
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModelObject);
var element = fileCodeModel.CodeElementFromPosition(location.SourceSpan.Start, EnvDTE.vsCMElement.vsCMElementFunction);
if (element != null)
{
overloadsBuilder.Add(element);
}
}
}
}
}
_overloads = overloadsBuilder.ToImmutableAndFree();
}
return _overloads;
}
internal override Snapshot CreateSnapshot() => new CodeElementSnapshot(GetOverloads());
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
if (index >= 0 && index < GetOverloads().Length)
{
element = GetOverloads()[index];
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
element = null;
return false;
}
public override int Count => GetOverloads().Length;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public sealed class OverloadsCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
CodeFunction parent)
{
var collection = new OverloadsCollection(state, parent);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private OverloadsCollection(
CodeModelState state,
CodeFunction parent)
: base(state, parent)
{
}
private ImmutableArray<EnvDTE.CodeElement> _overloads;
private CodeFunction ParentElement => (CodeFunction)this.Parent;
private ImmutableArray<EnvDTE.CodeElement> GetOverloads()
{
// Retrieving the overloads is potentially very expensive because it can force multiple FileCodeModels to be instantiated.
// Here, we cache the result to avoid having to perform these calculations each time GetOverloads() is called.
// This *could* be an issue because it means that an OverloadsCollection will not necessarily reflect the
// current state of the user's code. However, because a new OverloadsCollection is created every time the Overloads
// property is accessed on CodeFunction, consumers would hit this behavior rarely.
if (_overloads == null)
{
var symbol = (IMethodSymbol)ParentElement.LookupSymbol();
// Only methods and constructors can be overloaded. However, all functions
// can successfully return a collection of overloaded functions; if not
// really overloaded, the collection contains just the original function.
if (symbol.MethodKind != MethodKind.Ordinary &&
symbol.MethodKind != MethodKind.Constructor)
{
return ImmutableArray.Create((EnvDTE.CodeElement)Parent);
}
var solution = this.Workspace.CurrentSolution;
var overloadsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance();
foreach (var method in symbol.ContainingType.GetMembers(symbol.Name))
{
if (method.Kind != SymbolKind.Method)
{
continue;
}
var location = method.Locations.FirstOrDefault(l => l.IsInSource);
if (location != null)
{
var document = solution.GetDocument(location.SourceTree);
if (document != null)
{
var fileCodeModelObject = this.Workspace.GetFileCodeModel(document.Id);
if (fileCodeModelObject != null)
{
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModelObject);
var element = fileCodeModel.CodeElementFromPosition(location.SourceSpan.Start, EnvDTE.vsCMElement.vsCMElementFunction);
if (element != null)
{
overloadsBuilder.Add(element);
}
}
}
}
}
_overloads = overloadsBuilder.ToImmutableAndFree();
}
return _overloads;
}
internal override Snapshot CreateSnapshot() => new CodeElementSnapshot(GetOverloads());
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
if (index >= 0 && index < GetOverloads().Length)
{
element = GetOverloads()[index];
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
element = null;
return false;
}
public override int Count => GetOverloads().Length;
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/ExternalAccess/FSharp/Internal/CommentSelection/FSharpCommentSelectionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.CommentSelection
{
[Shared]
[ExportLanguageService(typeof(ICommentSelectionService), LanguageNames.FSharp)]
internal class FSharpCommentSelectionService : ICommentSelectionService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpCommentSelectionService()
{
}
public Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, CancellationToken cancellationToken)
{
return Task.FromResult(document);
}
public Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
return Task.FromResult(new CommentSelectionInfo(
supportsSingleLineComment: true,
supportsBlockComment: true,
singleLineCommentString: "//",
blockCommentStartString: "(*",
blockCommentEndString: "*)"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.CommentSelection
{
[Shared]
[ExportLanguageService(typeof(ICommentSelectionService), LanguageNames.FSharp)]
internal class FSharpCommentSelectionService : ICommentSelectionService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpCommentSelectionService()
{
}
public Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, CancellationToken cancellationToken)
{
return Task.FromResult(document);
}
public Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
return Task.FromResult(new CommentSelectionInfo(
supportsSingleLineComment: true,
supportsBlockComment: true,
singleLineCommentString: "//",
blockCommentStartString: "(*",
blockCommentEndString: "*)"));
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Emitter/Model/MostCommonNullableValueBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct MostCommonNullableValueBuilder
{
private int _value0;
private int _value1;
private int _value2;
internal byte? MostCommonValue
{
get
{
int max;
byte b;
if (_value1 > _value0)
{
max = _value1;
b = 1;
}
else
{
max = _value0;
b = 0;
}
if (_value2 > max)
{
return 2;
}
return max == 0 ? (byte?)null : b;
}
}
internal void AddValue(byte value)
{
switch (value)
{
case 0:
_value0++;
break;
case 1:
_value1++;
break;
case 2:
_value2++;
break;
default:
throw ExceptionUtilities.UnexpectedValue(value);
}
}
internal void AddValue(byte? value)
{
if (value != null)
{
AddValue(value.GetValueOrDefault());
}
}
internal void AddValue(TypeWithAnnotations type)
{
var builder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(builder);
AddValue(GetCommonValue(builder));
builder.Free();
}
/// <summary>
/// Returns the common value if all bytes are the same value.
/// Otherwise returns null.
/// </summary>
internal static byte? GetCommonValue(ArrayBuilder<byte> builder)
{
int n = builder.Count;
if (n == 0)
{
return null;
}
byte b = builder[0];
for (int i = 1; i < n; i++)
{
if (builder[i] != b)
{
return null;
}
}
return b;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct MostCommonNullableValueBuilder
{
private int _value0;
private int _value1;
private int _value2;
internal byte? MostCommonValue
{
get
{
int max;
byte b;
if (_value1 > _value0)
{
max = _value1;
b = 1;
}
else
{
max = _value0;
b = 0;
}
if (_value2 > max)
{
return 2;
}
return max == 0 ? (byte?)null : b;
}
}
internal void AddValue(byte value)
{
switch (value)
{
case 0:
_value0++;
break;
case 1:
_value1++;
break;
case 2:
_value2++;
break;
default:
throw ExceptionUtilities.UnexpectedValue(value);
}
}
internal void AddValue(byte? value)
{
if (value != null)
{
AddValue(value.GetValueOrDefault());
}
}
internal void AddValue(TypeWithAnnotations type)
{
var builder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(builder);
AddValue(GetCommonValue(builder));
builder.Free();
}
/// <summary>
/// Returns the common value if all bytes are the same value.
/// Otherwise returns null.
/// </summary>
internal static byte? GetCommonValue(ArrayBuilder<byte> builder)
{
int n = builder.Count;
if (n == 0)
{
return null;
}
byte b = builder[0];
for (int i = 1; i < n; i++)
{
if (builder[i] != b)
{
return null;
}
}
return b;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Collections/IdentifierCollection.Collection.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class IdentifierCollection
{
private abstract class CollectionBase : ICollection<string>
{
protected readonly IdentifierCollection IdentifierCollection;
private int _count = -1;
protected CollectionBase(IdentifierCollection identifierCollection)
{
this.IdentifierCollection = identifierCollection;
}
public abstract bool Contains(string item);
public void CopyTo(string[] array, int arrayIndex)
{
using (var enumerator = this.GetEnumerator())
{
while (arrayIndex < array.Length && enumerator.MoveNext())
{
array[arrayIndex] = enumerator.Current;
arrayIndex++;
}
}
}
public int Count
{
get
{
if (_count == -1)
{
_count = this.IdentifierCollection._map.Values.Sum(o => o is string ? 1 : ((ISet<string>)o).Count);
}
return _count;
}
}
public bool IsReadOnly => true;
public IEnumerator<string> GetEnumerator()
{
foreach (var obj in this.IdentifierCollection._map.Values)
{
var strs = obj as HashSet<string>;
if (strs != null)
{
foreach (var s in strs)
{
yield return s;
}
}
else
{
yield return (string)obj;
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#region Unsupported
public void Add(string item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Remove(string item)
{
throw new NotSupportedException();
}
#endregion
}
private sealed class CaseSensitiveCollection : CollectionBase
{
public CaseSensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection)
{
}
public override bool Contains(string item) => IdentifierCollection.CaseSensitiveContains(item);
}
private sealed class CaseInsensitiveCollection : CollectionBase
{
public CaseInsensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection)
{
}
public override bool Contains(string item) => IdentifierCollection.CaseInsensitiveContains(item);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class IdentifierCollection
{
private abstract class CollectionBase : ICollection<string>
{
protected readonly IdentifierCollection IdentifierCollection;
private int _count = -1;
protected CollectionBase(IdentifierCollection identifierCollection)
{
this.IdentifierCollection = identifierCollection;
}
public abstract bool Contains(string item);
public void CopyTo(string[] array, int arrayIndex)
{
using (var enumerator = this.GetEnumerator())
{
while (arrayIndex < array.Length && enumerator.MoveNext())
{
array[arrayIndex] = enumerator.Current;
arrayIndex++;
}
}
}
public int Count
{
get
{
if (_count == -1)
{
_count = this.IdentifierCollection._map.Values.Sum(o => o is string ? 1 : ((ISet<string>)o).Count);
}
return _count;
}
}
public bool IsReadOnly => true;
public IEnumerator<string> GetEnumerator()
{
foreach (var obj in this.IdentifierCollection._map.Values)
{
var strs = obj as HashSet<string>;
if (strs != null)
{
foreach (var s in strs)
{
yield return s;
}
}
else
{
yield return (string)obj;
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#region Unsupported
public void Add(string item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Remove(string item)
{
throw new NotSupportedException();
}
#endregion
}
private sealed class CaseSensitiveCollection : CollectionBase
{
public CaseSensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection)
{
}
public override bool Contains(string item) => IdentifierCollection.CaseSensitiveContains(item);
}
private sealed class CaseInsensitiveCollection : CollectionBase
{
public CaseInsensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection)
{
}
public override bool Contains(string item) => IdentifierCollection.CaseInsensitiveContains(item);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/CodeActions/Annotations/NavigationAnnotation.cs | // Licensed to the .NET Foundation under one or more 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.CodeActions
{
/// <summary>
/// Apply this annotation to an appropriate Syntax element to request that it should be
/// navigated to by the user after a code action is applied. If present the host should
/// try to place the user's caret at the beginning of the element.
/// </summary>
/// <remarks>
/// By using a <see cref="SyntaxAnnotation"/> this navigation location will be resilient
/// to the transformations performed by the <see cref="CodeAction"/> infrastructure.
/// Namely it will be resilient to the formatting, reduction or case correction that
/// automatically occures. This allows a code action to specify a desired location for
/// the user caret to be placed without knowing what actual position that location will
/// end up at when the action is finally applied.
/// </remarks>
internal static class NavigationAnnotation
{
public const string Kind = "CodeAction_Navigation";
public static SyntaxAnnotation Create()
=> new(Kind);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeActions
{
/// <summary>
/// Apply this annotation to an appropriate Syntax element to request that it should be
/// navigated to by the user after a code action is applied. If present the host should
/// try to place the user's caret at the beginning of the element.
/// </summary>
/// <remarks>
/// By using a <see cref="SyntaxAnnotation"/> this navigation location will be resilient
/// to the transformations performed by the <see cref="CodeAction"/> infrastructure.
/// Namely it will be resilient to the formatting, reduction or case correction that
/// automatically occures. This allows a code action to specify a desired location for
/// the user caret to be placed without knowing what actual position that location will
/// end up at when the action is finally applied.
/// </remarks>
internal static class NavigationAnnotation
{
public const string Kind = "CodeAction_Navigation";
public static SyntaxAnnotation Create()
=> new(Kind);
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAutoPropertyToFullProperty
{
public partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider();
[Theory, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
[InlineData("set"), InlineData("init")]
[WorkItem(48133, "https://github.com/dotnet/roslyn/issues/48133")]
public async Task SimpleAutoPropertyTest(string setter)
{
var text = $@"
class TestClass
{{
public int G[||]oo {{ get; {setter}; }}
}}
";
var expected = $@"
class TestClass
{{
private int goo;
public int Goo
{{
get
{{
return goo;
}}
{setter}
{{
goo = value;
}}
}}
}}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExtraLineAfterProperty()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithInitialValue()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; } = 2
}
";
var expected = @"
class TestClass
{
private int goo = 2;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithCalculatedInitialValue()
{
var text = @"
class TestClass
{
const int num = 345;
public int G[||]oo { get; set; } = 2*num
}
";
var expected = @"
class TestClass
{
const int num = 345;
private int goo = 2 * num;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithPrivateSetter()
{
var text = @"
class TestClass
{
public int G[||]oo { get; private set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
private set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithFieldNameAlreadyUsed()
{
var text = @"
class TestClass
{
private int goo;
public int G[||]oo { get; private set; }
}
";
var expected = @"
class TestClass
{
private int goo;
private int goo1;
public int Goo
{
get
{
return goo1;
}
private set
{
goo1 = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithComments()
{
var text = @"
class TestClass
{
// Comments before
public int G[||]oo { get; private set; } //Comments during
//Comments after
}
";
var expected = @"
class TestClass
{
private int goo;
// Comments before
public int Goo
{
get
{
return goo;
}
private set
{
goo = value;
}
} //Comments during
//Comments after
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBody()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get => goo; set => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWhenOnSingleLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get => goo; set => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWhenOnSingleLine2()
{
var text = @"
class TestClass
{
public int G[||]oo
{
get;
set;
}
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get => goo;
set => goo = value;
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWithTrivia()
{
var text = @"
class TestClass
{
public int G[||]oo { get /* test */ ; set /* test2 */ ; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get /* test */ => goo; set /* test2 */ => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithPropertyOpenBraceOnSameLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo {
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithAccessorOpenBraceOnSameLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get {
return goo;
}
set {
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task StaticProperty()
{
var text = @"
class TestClass
{
public static int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private static int goo;
public static int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ProtectedProperty()
{
var text = @"
class TestClass
{
protected int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
protected int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InternalProperty()
{
var text = @"
class TestClass
{
internal int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
internal int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithAttributes()
{
var text = @"
class TestClass
{
[A]
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
[A]
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CommentsInAccessors()
{
var text = @"
class TestClass
{
/// <summary>
/// test stuff here
/// </summary>
public int Testg[||]oo { /* test1 */ get /* test2 */; /* test3 */ set /* test4 */; /* test5 */ } /* test6 */
}
";
var expected = @"
class TestClass
{
private int testgoo;
/// <summary>
/// test stuff here
/// </summary>
public int Testgoo
{ /* test1 */
get /* test2 */
{
return testgoo;
} /* test3 */
set /* test4 */
{
testgoo = value;
} /* test5 */
} /* test6 */
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task OverrideProperty()
{
var text = @"
class MyBaseClass
{
public virtual string Name { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string N[||]ame {get; set;}
}
";
var expected = @"
class MyBaseClass
{
public virtual string Name { get; set; }
}
class MyDerivedClass : MyBaseClass
{
private string name;
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SealedProperty()
{
var text = @"
class MyClass
{
public sealed string N[||]ame {get; set;}
}
";
var expected = @"
class MyClass
{
private string name;
public sealed string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task VirtualProperty()
{
var text = @"
class MyBaseClass
{
public virtual string N[||]ame { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
var expected = @"
class MyBaseClass
{
private string name;
public virtual string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PrivateProperty()
{
var text = @"
class MyClass
{
private string N[||]ame { get; set; }
}
";
var expected = @"
class MyClass
{
private string name;
private string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task AbstractProperty()
{
var text = @"
class MyBaseClass
{
public abstract string N[||]ame { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExternProperty()
{
var text = @"
class MyBaseClass
{
extern string N[||]ame { get; set; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task GetterOnly()
{
var text = @"
class TestClass
{
public int G[||]oo { get;}
}
";
var expected = @"
class TestClass
{
private readonly int goo;
public int Goo
{
get
{
return goo;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task GetterOnlyExpressionBodies()
{
var text = @"
class TestClass
{
public int G[||]oo { get;}
}
";
var expected = @"
class TestClass
{
private readonly int goo;
public int Goo => goo;
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SetterOnly()
{
var text = @"
class TestClass
{
public int G[||]oo
{
set {}
}
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExpressionBodiedAccessors()
{
var text = @"
class TestClass
{
private int testgoo;
public int testg[||]oo {get => testgoo; set => testgoo = value; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorAtBeginning()
{
var text = @"
class TestClass
{
[||]public int Goo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorAtEnd()
{
var text = @"
class TestClass
{
public int Goo[||] { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorOnAccessors()
{
var text = @"
class TestClass
{
public int Goo { g[||]et; set; }
}
";
await TestMissingAsync(text);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorInType()
{
var text = @"
class TestClass
{
public in[||]t Goo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SelectionWhole()
{
var text = @"
class TestClass
{
[|public int Goo { get; set; }|]
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SelectionName()
{
var text = @"
class TestClass
{
public int [|Goo|] { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task MoreThanOneGetter()
{
var text = @"
class TestClass
{
public int Goo { g[||]et; get; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task MoreThanOneSetter()
{
var text = @"
class TestClass
{
public int Goo { get; s[||]et; set; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CustomFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int testingGoo;
public int Goo
{
get
{
return testingGoo;
}
set
{
testingGoo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomFieldName);
}
[WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task UnderscorePrefixedFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int _goo;
public int Goo
{
get
{
return _goo;
}
set
{
_goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseUnderscorePrefixedFieldName);
}
[WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PropertyNameEqualsToClassNameExceptFirstCharCasingWhichCausesFieldNameCollisionByDefault()
{
var text = @"
class stranger
{
public int S[||]tranger { get; set; }
}
";
var expected = @"
class stranger
{
private int stranger;
public int Stranger { get => stranger; set => stranger = value; }
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task NonStaticPropertyWithCustomStaticFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task StaticPropertyWithCustomStaticFieldName()
{
var text = @"
class TestClass
{
public static int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private static int staticfieldtestGoo;
public static int Goo
{
get
{
return staticfieldtestGoo;
}
set
{
staticfieldtestGoo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InInterface()
{
var text = @"
interface IGoo
{
public int Goo { get; s[||]et; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InStruct()
{
var text = @"
struct goo
{
public int G[||]oo { get; set; }
}
";
var expected = @"
struct goo
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClasses()
{
var text = @"
partial class Program
{
int P { get; set; }
}
partial class Program
{
int [||]Q { get; set; }
}
";
var expected = @"
partial class Program
{
int P { get; set; }
}
partial class Program
{
private int q;
int Q { get => q; set => q = value; }
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClassInSeparateFiles1()
{
var file1 = @"
partial class Program
{
int [||]P { get; set; }
}";
var file2 = @"
partial class Program
{
int Q { get; set; }
}";
var file1AfterRefactor = @"
partial class Program
{
private int p;
int P { get => p; set => p = value; }
}";
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""file1"">{1}</Document>
<Document FilePath=""file2"">{2}</Document>
</Project>
</Workspace>", LanguageNames.CSharp, file1, file2);
using var testWorkspace = TestWorkspace.Create(xmlString);
// refactor file1 and check
var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default);
await TestActionAsync(
testWorkspace,
file1AfterRefactor,
action,
conflictSpans: ImmutableArray<TextSpan>.Empty,
renameSpans: ImmutableArray<TextSpan>.Empty,
warningSpans: ImmutableArray<TextSpan>.Empty,
navigationSpans: ImmutableArray<TextSpan>.Empty,
parameters: default);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClassInSeparateFiles2()
{
var file1 = @"
partial class Program
{
int P { get; set; }
}";
var file2 = @"
partial class Program
{
int Q[||] { get; set; }
}";
var file2AfterRefactor = @"
partial class Program
{
private int q;
int Q { get => q; set => q = value; }
}";
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""file1"">{1}</Document>
<Document FilePath=""file2"">{2}</Document>
</Project>
</Workspace>", LanguageNames.CSharp, file1, file2);
using var testWorkspace = TestWorkspace.Create(xmlString);
// refactor file2 and check
var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default);
await TestActionAsync(
testWorkspace,
file2AfterRefactor,
action,
conflictSpans: ImmutableArray<TextSpan>.Empty,
renameSpans: ImmutableArray<TextSpan>.Empty,
warningSpans: ImmutableArray<TextSpan>.Empty,
navigationSpans: ImmutableArray<TextSpan>.Empty,
parameters: default);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InvalidLocation()
{
await TestMissingAsync(@"namespace NS
{
public int G[||]oo { get; set; }
}");
await TestMissingAsync("public int G[||]oo { get; set; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task NullBackingField()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class Program
{
string? Name[||] { get; set; }
}",
@"
#nullable enable
class Program
{
private string? name;
string? Name { get => name; set => name = 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.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.ConvertAutoPropertyToFullProperty;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAutoPropertyToFullProperty
{
public partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpConvertAutoPropertyToFullPropertyCodeRefactoringProvider();
[Theory, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
[InlineData("set"), InlineData("init")]
[WorkItem(48133, "https://github.com/dotnet/roslyn/issues/48133")]
public async Task SimpleAutoPropertyTest(string setter)
{
var text = $@"
class TestClass
{{
public int G[||]oo {{ get; {setter}; }}
}}
";
var expected = $@"
class TestClass
{{
private int goo;
public int Goo
{{
get
{{
return goo;
}}
{setter}
{{
goo = value;
}}
}}
}}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExtraLineAfterProperty()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithInitialValue()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; } = 2
}
";
var expected = @"
class TestClass
{
private int goo = 2;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithCalculatedInitialValue()
{
var text = @"
class TestClass
{
const int num = 345;
public int G[||]oo { get; set; } = 2*num
}
";
var expected = @"
class TestClass
{
const int num = 345;
private int goo = 2 * num;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithPrivateSetter()
{
var text = @"
class TestClass
{
public int G[||]oo { get; private set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
private set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithFieldNameAlreadyUsed()
{
var text = @"
class TestClass
{
private int goo;
public int G[||]oo { get; private set; }
}
";
var expected = @"
class TestClass
{
private int goo;
private int goo1;
public int Goo
{
get
{
return goo1;
}
private set
{
goo1 = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithComments()
{
var text = @"
class TestClass
{
// Comments before
public int G[||]oo { get; private set; } //Comments during
//Comments after
}
";
var expected = @"
class TestClass
{
private int goo;
// Comments before
public int Goo
{
get
{
return goo;
}
private set
{
goo = value;
}
} //Comments during
//Comments after
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBody()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get => goo; set => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWhenOnSingleLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get => goo; set => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWhenOnSingleLine2()
{
var text = @"
class TestClass
{
public int G[||]oo
{
get;
set;
}
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get => goo;
set => goo = value;
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenOnSingleLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithExpressionBodyWithTrivia()
{
var text = @"
class TestClass
{
public int G[||]oo { get /* test */ ; set /* test2 */ ; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo { get /* test */ => goo; set /* test2 */ => goo = value; }
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiedAccessorsWhenPossible);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithPropertyOpenBraceOnSameLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo {
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithAccessorOpenBraceOnSameLine()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get {
return goo;
}
set {
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task StaticProperty()
{
var text = @"
class TestClass
{
public static int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private static int goo;
public static int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ProtectedProperty()
{
var text = @"
class TestClass
{
protected int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
protected int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InternalProperty()
{
var text = @"
class TestClass
{
internal int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
internal int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task WithAttributes()
{
var text = @"
class TestClass
{
[A]
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
[A]
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CommentsInAccessors()
{
var text = @"
class TestClass
{
/// <summary>
/// test stuff here
/// </summary>
public int Testg[||]oo { /* test1 */ get /* test2 */; /* test3 */ set /* test4 */; /* test5 */ } /* test6 */
}
";
var expected = @"
class TestClass
{
private int testgoo;
/// <summary>
/// test stuff here
/// </summary>
public int Testgoo
{ /* test1 */
get /* test2 */
{
return testgoo;
} /* test3 */
set /* test4 */
{
testgoo = value;
} /* test5 */
} /* test6 */
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task OverrideProperty()
{
var text = @"
class MyBaseClass
{
public virtual string Name { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string N[||]ame {get; set;}
}
";
var expected = @"
class MyBaseClass
{
public virtual string Name { get; set; }
}
class MyDerivedClass : MyBaseClass
{
private string name;
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SealedProperty()
{
var text = @"
class MyClass
{
public sealed string N[||]ame {get; set;}
}
";
var expected = @"
class MyClass
{
private string name;
public sealed string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task VirtualProperty()
{
var text = @"
class MyBaseClass
{
public virtual string N[||]ame { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
var expected = @"
class MyBaseClass
{
private string name;
public virtual string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PrivateProperty()
{
var text = @"
class MyClass
{
private string N[||]ame { get; set; }
}
";
var expected = @"
class MyClass
{
private string name;
private string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task AbstractProperty()
{
var text = @"
class MyBaseClass
{
public abstract string N[||]ame { get; set; }
}
class MyDerivedClass : MyBaseClass
{
public override string Name {get; set;}
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExternProperty()
{
var text = @"
class MyBaseClass
{
extern string N[||]ame { get; set; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task GetterOnly()
{
var text = @"
class TestClass
{
public int G[||]oo { get;}
}
";
var expected = @"
class TestClass
{
private readonly int goo;
public int Goo
{
get
{
return goo;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task GetterOnlyExpressionBodies()
{
var text = @"
class TestClass
{
public int G[||]oo { get;}
}
";
var expected = @"
class TestClass
{
private readonly int goo;
public int Goo => goo;
}
";
await TestInRegularAndScriptAsync(text, expected, options: PreferExpressionBodiesOnAccessorsAndMethods);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SetterOnly()
{
var text = @"
class TestClass
{
public int G[||]oo
{
set {}
}
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task ExpressionBodiedAccessors()
{
var text = @"
class TestClass
{
private int testgoo;
public int testg[||]oo {get => testgoo; set => testgoo = value; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorAtBeginning()
{
var text = @"
class TestClass
{
[||]public int Goo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorAtEnd()
{
var text = @"
class TestClass
{
public int Goo[||] { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorOnAccessors()
{
var text = @"
class TestClass
{
public int Goo { g[||]et; set; }
}
";
await TestMissingAsync(text);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CursorInType()
{
var text = @"
class TestClass
{
public in[||]t Goo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SelectionWhole()
{
var text = @"
class TestClass
{
[|public int Goo { get; set; }|]
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task SelectionName()
{
var text = @"
class TestClass
{
public int [|Goo|] { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task MoreThanOneGetter()
{
var text = @"
class TestClass
{
public int Goo { g[||]et; get; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task MoreThanOneSetter()
{
var text = @"
class TestClass
{
public int Goo { get; s[||]et; set; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task CustomFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int testingGoo;
public int Goo
{
get
{
return testingGoo;
}
set
{
testingGoo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomFieldName);
}
[WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task UnderscorePrefixedFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int _goo;
public int Goo
{
get
{
return _goo;
}
set
{
_goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseUnderscorePrefixedFieldName);
}
[WorkItem(28013, "https://github.com/dotnet/roslyn/issues/26992")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PropertyNameEqualsToClassNameExceptFirstCharCasingWhichCausesFieldNameCollisionByDefault()
{
var text = @"
class stranger
{
public int S[||]tranger { get; set; }
}
";
var expected = @"
class stranger
{
private int stranger;
public int Stranger { get => stranger; set => stranger = value; }
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task NonStaticPropertyWithCustomStaticFieldName()
{
var text = @"
class TestClass
{
public int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task StaticPropertyWithCustomStaticFieldName()
{
var text = @"
class TestClass
{
public static int G[||]oo { get; set; }
}
";
var expected = @"
class TestClass
{
private static int staticfieldtestGoo;
public static int Goo
{
get
{
return staticfieldtestGoo;
}
set
{
staticfieldtestGoo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: UseCustomStaticFieldName);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InInterface()
{
var text = @"
interface IGoo
{
public int Goo { get; s[||]et; }
}
";
await TestMissingAsync(text);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InStruct()
{
var text = @"
struct goo
{
public int G[||]oo { get; set; }
}
";
var expected = @"
struct goo
{
private int goo;
public int Goo
{
get
{
return goo;
}
set
{
goo = value;
}
}
}
";
await TestInRegularAndScriptAsync(text, expected, options: DoNotPreferExpressionBodiedAccessors);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClasses()
{
var text = @"
partial class Program
{
int P { get; set; }
}
partial class Program
{
int [||]Q { get; set; }
}
";
var expected = @"
partial class Program
{
int P { get; set; }
}
partial class Program
{
private int q;
int Q { get => q; set => q = value; }
}
";
await TestInRegularAndScriptAsync(text, expected);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClassInSeparateFiles1()
{
var file1 = @"
partial class Program
{
int [||]P { get; set; }
}";
var file2 = @"
partial class Program
{
int Q { get; set; }
}";
var file1AfterRefactor = @"
partial class Program
{
private int p;
int P { get => p; set => p = value; }
}";
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""file1"">{1}</Document>
<Document FilePath=""file2"">{2}</Document>
</Project>
</Workspace>", LanguageNames.CSharp, file1, file2);
using var testWorkspace = TestWorkspace.Create(xmlString);
// refactor file1 and check
var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default);
await TestActionAsync(
testWorkspace,
file1AfterRefactor,
action,
conflictSpans: ImmutableArray<TextSpan>.Empty,
renameSpans: ImmutableArray<TextSpan>.Empty,
warningSpans: ImmutableArray<TextSpan>.Empty,
navigationSpans: ImmutableArray<TextSpan>.Empty,
parameters: default);
}
[WorkItem(22146, "https://github.com/dotnet/roslyn/issues/22146")]
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task PartialClassInSeparateFiles2()
{
var file1 = @"
partial class Program
{
int P { get; set; }
}";
var file2 = @"
partial class Program
{
int Q[||] { get; set; }
}";
var file2AfterRefactor = @"
partial class Program
{
private int q;
int Q { get => q; set => q = value; }
}";
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""file1"">{1}</Document>
<Document FilePath=""file2"">{2}</Document>
</Project>
</Workspace>", LanguageNames.CSharp, file1, file2);
using var testWorkspace = TestWorkspace.Create(xmlString);
// refactor file2 and check
var (_, action) = await GetCodeActionsAsync(testWorkspace, parameters: default);
await TestActionAsync(
testWorkspace,
file2AfterRefactor,
action,
conflictSpans: ImmutableArray<TextSpan>.Empty,
renameSpans: ImmutableArray<TextSpan>.Empty,
warningSpans: ImmutableArray<TextSpan>.Empty,
navigationSpans: ImmutableArray<TextSpan>.Empty,
parameters: default);
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task InvalidLocation()
{
await TestMissingAsync(@"namespace NS
{
public int G[||]oo { get; set; }
}");
await TestMissingAsync("public int G[||]oo { get; set; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.ConvertAutoPropertyToFullProperty)]
public async Task NullBackingField()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class Program
{
string? Name[||] { get; set; }
}",
@"
#nullable enable
class Program
{
private string? name;
string? Name { get => name; set => name = value; }
}");
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/CSharp/Test/ProjectSystemShim/VisualStudioCompilationOutputFilesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.UnitTests
{
public class VisualStudioCompilationOutputFilesTests : TestBase
{
[Fact]
public void OpenStream_Errors()
{
Assert.Throws<ArgumentException>(() => new CompilationOutputFilesWithImplicitPdbPath(@"a.dll"));
}
[Theory]
[InlineData(DebugInformationFormat.PortablePdb, true)]
[InlineData(DebugInformationFormat.PortablePdb, false)]
[InlineData(DebugInformationFormat.Embedded, false)]
public void AssemblyAndPdb(DebugInformationFormat pdbFormat, bool exactPdbPath)
{
var dir = Temp.CreateDirectory();
var dllFile = dir.CreateFile("lib.dll");
var pdbFile = (pdbFormat == DebugInformationFormat.Embedded) ? null : dir.CreateFile("lib.pdb");
var source = @"class C { public static void Main() { int x = 1; } }";
var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, assemblyName: "lib");
var pdbStream = (pdbFile != null) ? new MemoryStream() : null;
var debugDirPdbPath = exactPdbPath ? pdbFile.Path : "a/y/z/lib.pdb";
var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: pdbFormat, pdbFilePath: debugDirPdbPath), pdbStream: pdbStream);
dllFile.WriteAllBytes(peImage);
if (pdbFile != null)
{
pdbStream.Position = 0;
pdbFile.WriteAllBytes(pdbStream.ToArray());
}
var outputs = new CompilationOutputFilesWithImplicitPdbPath(dllFile.Path);
using (var pdb = outputs.OpenPdb())
{
var encReader = pdb.CreateEditAndContinueMethodDebugInfoReader();
Assert.True(encReader.IsPortable);
var localSig = encReader.GetLocalSignature(MetadataTokens.MethodDefinitionHandle(1));
Assert.Equal(MetadataTokens.StandaloneSignatureHandle(1), localSig);
}
using (var metadata = outputs.OpenAssemblyMetadata(prefetch: false))
{
var mdReader = metadata.GetMetadataReader();
Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name));
}
// make sure all files are closed and can be deleted
Directory.Delete(dir.Path, recursive: true);
}
[Fact]
public void AssemblyFileNotFound()
{
var dir = Temp.CreateDirectory();
var outputs = new CompilationOutputFilesWithImplicitPdbPath(Path.Combine(dir.Path, "nonexistent.dll"));
Assert.Null(outputs.OpenPdb());
Assert.Null(outputs.OpenAssemblyMetadata(prefetch: false));
}
[Fact]
public void PdbFileNotFound()
{
var dir = Temp.CreateDirectory();
var dllFile = dir.CreateFile("lib.dll");
var source = @"class C { public static void Main() { int x = 1; } }";
var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, assemblyName: "lib");
var pdbStream = new MemoryStream();
var debugDirPdbPath = Path.Combine(dir.Path, "nonexistent.pdb");
var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: debugDirPdbPath), pdbStream: pdbStream);
pdbStream.Position = 0;
dllFile.WriteAllBytes(peImage);
var outputs = new CompilationOutputFilesWithImplicitPdbPath(dllFile.Path);
Assert.Null(outputs.OpenPdb());
using (var metadata = outputs.OpenAssemblyMetadata(prefetch: false))
{
var mdReader = metadata.GetMetadataReader();
Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name));
}
// make sure all files are closed and can be deleted
Directory.Delete(dir.Path, recursive: 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.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.UnitTests
{
public class VisualStudioCompilationOutputFilesTests : TestBase
{
[Fact]
public void OpenStream_Errors()
{
Assert.Throws<ArgumentException>(() => new CompilationOutputFilesWithImplicitPdbPath(@"a.dll"));
}
[Theory]
[InlineData(DebugInformationFormat.PortablePdb, true)]
[InlineData(DebugInformationFormat.PortablePdb, false)]
[InlineData(DebugInformationFormat.Embedded, false)]
public void AssemblyAndPdb(DebugInformationFormat pdbFormat, bool exactPdbPath)
{
var dir = Temp.CreateDirectory();
var dllFile = dir.CreateFile("lib.dll");
var pdbFile = (pdbFormat == DebugInformationFormat.Embedded) ? null : dir.CreateFile("lib.pdb");
var source = @"class C { public static void Main() { int x = 1; } }";
var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, assemblyName: "lib");
var pdbStream = (pdbFile != null) ? new MemoryStream() : null;
var debugDirPdbPath = exactPdbPath ? pdbFile.Path : "a/y/z/lib.pdb";
var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: pdbFormat, pdbFilePath: debugDirPdbPath), pdbStream: pdbStream);
dllFile.WriteAllBytes(peImage);
if (pdbFile != null)
{
pdbStream.Position = 0;
pdbFile.WriteAllBytes(pdbStream.ToArray());
}
var outputs = new CompilationOutputFilesWithImplicitPdbPath(dllFile.Path);
using (var pdb = outputs.OpenPdb())
{
var encReader = pdb.CreateEditAndContinueMethodDebugInfoReader();
Assert.True(encReader.IsPortable);
var localSig = encReader.GetLocalSignature(MetadataTokens.MethodDefinitionHandle(1));
Assert.Equal(MetadataTokens.StandaloneSignatureHandle(1), localSig);
}
using (var metadata = outputs.OpenAssemblyMetadata(prefetch: false))
{
var mdReader = metadata.GetMetadataReader();
Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name));
}
// make sure all files are closed and can be deleted
Directory.Delete(dir.Path, recursive: true);
}
[Fact]
public void AssemblyFileNotFound()
{
var dir = Temp.CreateDirectory();
var outputs = new CompilationOutputFilesWithImplicitPdbPath(Path.Combine(dir.Path, "nonexistent.dll"));
Assert.Null(outputs.OpenPdb());
Assert.Null(outputs.OpenAssemblyMetadata(prefetch: false));
}
[Fact]
public void PdbFileNotFound()
{
var dir = Temp.CreateDirectory();
var dllFile = dir.CreateFile("lib.dll");
var source = @"class C { public static void Main() { int x = 1; } }";
var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, assemblyName: "lib");
var pdbStream = new MemoryStream();
var debugDirPdbPath = Path.Combine(dir.Path, "nonexistent.pdb");
var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: debugDirPdbPath), pdbStream: pdbStream);
pdbStream.Position = 0;
dllFile.WriteAllBytes(peImage);
var outputs = new CompilationOutputFilesWithImplicitPdbPath(dllFile.Path);
Assert.Null(outputs.OpenPdb());
using (var metadata = outputs.OpenAssemblyMetadata(prefetch: false))
{
var mdReader = metadata.GetMetadataReader();
Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name));
}
// make sure all files are closed and can be deleted
Directory.Delete(dir.Path, recursive: true);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTriviaListExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class SyntaxTriviaListExtensions
{
public static bool Any(this SyntaxTriviaList triviaList, params SyntaxKind[] kinds)
{
foreach (var trivia in triviaList)
{
if (trivia.MatchesKind(kinds))
{
return true;
}
}
return false;
}
public static SyntaxTrivia? GetFirstNewLine(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.Kind() == SyntaxKind.EndOfLineTrivia)
.FirstOrNull();
}
public static SyntaxTrivia? GetLastComment(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.IsRegularComment())
.LastOrNull();
}
public static SyntaxTrivia? GetLastCommentOrWhitespace(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.MatchesKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia, SyntaxKind.WhitespaceTrivia))
.LastOrNull();
}
public static IEnumerable<SyntaxTrivia> SkipInitialWhitespace(this SyntaxTriviaList triviaList)
=> triviaList.SkipWhile(t => t.Kind() == SyntaxKind.WhitespaceTrivia);
private static ImmutableArray<ImmutableArray<SyntaxTrivia>> GetLeadingBlankLines(SyntaxTriviaList triviaList)
{
using var result = TemporaryArray<ImmutableArray<SyntaxTrivia>>.Empty;
using var currentLine = TemporaryArray<SyntaxTrivia>.Empty;
foreach (var trivia in triviaList)
{
currentLine.Add(trivia);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
var currentLineIsBlank = currentLine.All(static t =>
t.Kind() == SyntaxKind.EndOfLineTrivia ||
t.Kind() == SyntaxKind.WhitespaceTrivia);
if (!currentLineIsBlank)
{
break;
}
result.Add(currentLine.ToImmutableAndClear());
}
}
return result.ToImmutableAndClear();
}
public static SyntaxTriviaList WithoutLeadingBlankLines(this SyntaxTriviaList triviaList)
{
var triviaInLeadingBlankLines = GetLeadingBlankLines(triviaList).SelectMany(l => l);
return new SyntaxTriviaList(triviaList.Skip(triviaInLeadingBlankLines.Count()));
}
/// <summary>
/// Takes an INCLUSIVE range of trivia from the trivia list.
/// </summary>
public static IEnumerable<SyntaxTrivia> TakeRange(this SyntaxTriviaList triviaList, int start, int end)
{
while (start <= end)
{
yield return triviaList[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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class SyntaxTriviaListExtensions
{
public static bool Any(this SyntaxTriviaList triviaList, params SyntaxKind[] kinds)
{
foreach (var trivia in triviaList)
{
if (trivia.MatchesKind(kinds))
{
return true;
}
}
return false;
}
public static SyntaxTrivia? GetFirstNewLine(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.Kind() == SyntaxKind.EndOfLineTrivia)
.FirstOrNull();
}
public static SyntaxTrivia? GetLastComment(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.IsRegularComment())
.LastOrNull();
}
public static SyntaxTrivia? GetLastCommentOrWhitespace(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.MatchesKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia, SyntaxKind.WhitespaceTrivia))
.LastOrNull();
}
public static IEnumerable<SyntaxTrivia> SkipInitialWhitespace(this SyntaxTriviaList triviaList)
=> triviaList.SkipWhile(t => t.Kind() == SyntaxKind.WhitespaceTrivia);
private static ImmutableArray<ImmutableArray<SyntaxTrivia>> GetLeadingBlankLines(SyntaxTriviaList triviaList)
{
using var result = TemporaryArray<ImmutableArray<SyntaxTrivia>>.Empty;
using var currentLine = TemporaryArray<SyntaxTrivia>.Empty;
foreach (var trivia in triviaList)
{
currentLine.Add(trivia);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
var currentLineIsBlank = currentLine.All(static t =>
t.Kind() == SyntaxKind.EndOfLineTrivia ||
t.Kind() == SyntaxKind.WhitespaceTrivia);
if (!currentLineIsBlank)
{
break;
}
result.Add(currentLine.ToImmutableAndClear());
}
}
return result.ToImmutableAndClear();
}
public static SyntaxTriviaList WithoutLeadingBlankLines(this SyntaxTriviaList triviaList)
{
var triviaInLeadingBlankLines = GetLeadingBlankLines(triviaList).SelectMany(l => l);
return new SyntaxTriviaList(triviaList.Skip(triviaInLeadingBlankLines.Count()));
}
/// <summary>
/// Takes an INCLUSIVE range of trivia from the trivia list.
/// </summary>
public static IEnumerable<SyntaxTrivia> TakeRange(this SyntaxTriviaList triviaList, int start, int end)
{
while (start <= end)
{
yield return triviaList[start++];
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/EmbeddedCompletionContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Completion;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions
{
internal partial class RegexEmbeddedCompletionProvider
{
private readonly struct EmbeddedCompletionContext
{
private readonly RegexEmbeddedLanguage _language;
private readonly CompletionContext _context;
private readonly HashSet<string> _names;
public readonly RegexTree Tree;
public readonly SyntaxToken StringToken;
public readonly int Position;
public readonly CompletionTrigger Trigger;
public readonly List<RegexItem> Items;
public EmbeddedCompletionContext(
RegexEmbeddedLanguage language,
CompletionContext context,
RegexTree tree,
SyntaxToken stringToken)
{
_language = language;
_context = context;
_names = new HashSet<string>();
Tree = tree;
StringToken = stringToken;
Position = _context.Position;
Trigger = _context.Trigger;
Items = new List<RegexItem>();
}
public void AddIfMissing(
string displayText, string suffix, string description,
RegexNode parentOpt, int? positionOffset = null, string insertionText = null)
{
var replacementStart = parentOpt != null
? parentOpt.GetSpan().Start
: Position;
var replacementSpan = TextSpan.FromBounds(replacementStart, Position);
var newPosition = replacementStart + positionOffset;
insertionText ??= displayText;
var escapedInsertionText = _language.EscapeText(insertionText, StringToken);
if (escapedInsertionText != insertionText)
{
newPosition += escapedInsertionText.Length - insertionText.Length;
}
AddIfMissing(new RegexItem(
displayText, suffix, description,
CompletionChange.Create(
new TextChange(replacementSpan, escapedInsertionText),
newPosition)));
}
public void AddIfMissing(RegexItem item)
{
if (_names.Add(item.DisplayText))
{
Items.Add(item);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Completion;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions
{
internal partial class RegexEmbeddedCompletionProvider
{
private readonly struct EmbeddedCompletionContext
{
private readonly RegexEmbeddedLanguage _language;
private readonly CompletionContext _context;
private readonly HashSet<string> _names;
public readonly RegexTree Tree;
public readonly SyntaxToken StringToken;
public readonly int Position;
public readonly CompletionTrigger Trigger;
public readonly List<RegexItem> Items;
public EmbeddedCompletionContext(
RegexEmbeddedLanguage language,
CompletionContext context,
RegexTree tree,
SyntaxToken stringToken)
{
_language = language;
_context = context;
_names = new HashSet<string>();
Tree = tree;
StringToken = stringToken;
Position = _context.Position;
Trigger = _context.Trigger;
Items = new List<RegexItem>();
}
public void AddIfMissing(
string displayText, string suffix, string description,
RegexNode parentOpt, int? positionOffset = null, string insertionText = null)
{
var replacementStart = parentOpt != null
? parentOpt.GetSpan().Start
: Position;
var replacementSpan = TextSpan.FromBounds(replacementStart, Position);
var newPosition = replacementStart + positionOffset;
insertionText ??= displayText;
var escapedInsertionText = _language.EscapeText(insertionText, StringToken);
if (escapedInsertionText != insertionText)
{
newPosition += escapedInsertionText.Length - insertionText.Length;
}
AddIfMissing(new RegexItem(
displayText, suffix, description,
CompletionChange.Create(
new TextChange(replacementSpan, escapedInsertionText),
newPosition)));
}
public void AddIfMissing(RegexItem item)
{
if (_names.Add(item.DisplayText))
{
Items.Add(item);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/Library/AbstractLibraryManager.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library
{
internal abstract partial class AbstractLibraryManager : IVsCoTaskMemFreeMyStrings
{
internal readonly Guid LibraryGuid;
private readonly IServiceProvider _serviceProvider;
private readonly IntPtr _imageListPtr;
protected AbstractLibraryManager(Guid libraryGuid, IServiceProvider serviceProvider)
{
LibraryGuid = libraryGuid;
_serviceProvider = serviceProvider;
var vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
vsShell?.TryGetPropertyValue(__VSSPROPID.VSSPROPID_ObjectMgrTypesImgList, out _imageListPtr);
}
public IServiceProvider ServiceProvider
{
get { return _serviceProvider; }
}
public IntPtr ImageListPtr
{
get { return _imageListPtr; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library
{
internal abstract partial class AbstractLibraryManager : IVsCoTaskMemFreeMyStrings
{
internal readonly Guid LibraryGuid;
private readonly IServiceProvider _serviceProvider;
private readonly IntPtr _imageListPtr;
protected AbstractLibraryManager(Guid libraryGuid, IServiceProvider serviceProvider)
{
LibraryGuid = libraryGuid;
_serviceProvider = serviceProvider;
var vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
vsShell?.TryGetPropertyValue(__VSSPROPID.VSSPROPID_ObjectMgrTypesImgList, out _imageListPtr);
}
public IServiceProvider ServiceProvider
{
get { return _serviceProvider; }
}
public IntPtr ImageListPtr
{
get { return _imageListPtr; }
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/Formatting/CSharpFormattingInteractionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Indentation;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
[ExportLanguageService(typeof(IFormattingInteractionService), LanguageNames.CSharp), Shared]
internal partial class CSharpFormattingInteractionService : IFormattingInteractionService
{
// All the characters that might potentially trigger formatting when typed
private readonly char[] _supportedChars = ";{}#nte:)".ToCharArray();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpFormattingInteractionService()
{
}
public bool SupportsFormatDocument => true;
public bool SupportsFormatOnPaste => true;
public bool SupportsFormatSelection => true;
public bool SupportsFormatOnReturn => false;
public bool SupportsFormattingOnTypedCharacter(Document document, char ch)
{
// Performance: This method checks several options to determine if we should do smart
// indent, none of which are controlled by editorconfig. Instead of calling
// document.GetOptionsAsync we can use the Workspace's global options and thus save the
// work of attempting to read in the editorconfig file.
var options = document.Project.Solution.Workspace.Options;
var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) == FormattingOptions.IndentStyle.Smart;
// We consider the proper placement of a close curly or open curly when it is typed at
// the start of the line to be a smart-indentation operation. As such, even if "format
// on typing" is off, if "smart indent" is on, we'll still format this. (However, we
// won't touch anything else in the block this close curly belongs to.).
//
// See extended comment in GetFormattingChangesAsync for more details on this.
if (smartIndentOn)
{
if (ch == '{' || ch == '}')
{
return true;
}
}
// If format-on-typing is not on, then we don't support formatting on any other characters.
var autoFormattingOnTyping = options.GetOption(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp);
if (!autoFormattingOnTyping)
{
return false;
}
if (ch == '}' && !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp))
{
return false;
}
if (ch == ';' && !options.GetOption(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp))
{
return false;
}
// don't auto format after these keys if smart indenting is not on.
if ((ch == '#' || ch == 'n') && !smartIndentOn)
{
return false;
}
return _supportedChars.Contains(ch);
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
TextSpan? textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var span = textSpan ?? new TextSpan(0, root.FullSpan.Length);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, span);
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: true, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root,
SpecializedCollections.SingletonEnumerable(formattingSpan),
document.Project.Solution.Workspace, options, cancellationToken).ToImmutableArray();
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync(
Document document,
TextSpan textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan);
var service = document.GetLanguageService<ISyntaxFormattingService>();
if (service == null)
{
return ImmutableArray<TextChange>.Empty;
}
var rules = new List<AbstractFormattingRule>() { new PasteFormattingRule() };
rules.AddRange(service.GetDefaultFormattingRules());
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, rules, cancellationToken).ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, SyntaxToken tokenBeforeCaret)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
return formattingRuleFactory.CreateRule(document, position).Concat(GetTypingRules(tokenBeforeCaret)).Concat(Formatter.GetDefaultFormattingRules(document));
}
Task<ImmutableArray<TextChange>> IFormattingInteractionService.GetFormattingChangesOnReturnAsync(
Document document, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken)
=> SpecializedTasks.EmptyImmutableArray<TextChange>();
private static async Task<bool> TokenShouldNotFormatOnTypeCharAsync(
SyntaxToken token, CancellationToken cancellationToken)
{
// If the token is a ) we only want to format if it's the close paren
// of a using statement. That way if we have nested usings, the inner
// using will align with the outer one when the user types the close paren.
if (token.IsKind(SyntaxKind.CloseParenToken) && !token.Parent.IsKind(SyntaxKind.UsingStatement))
{
return true;
}
// If the token is a : we only want to format if it's a labeled statement
// or case. When the colon is typed we'll want ot immediately have those
// statements snap to their appropriate indentation level.
if (token.IsKind(SyntaxKind.ColonToken) && !(token.Parent.IsKind(SyntaxKind.LabeledStatement) || token.Parent is SwitchLabelSyntax))
{
return true;
}
// Only format an { if it is the first token on a line. We don't want to
// mess with it if it's inside a line.
if (token.IsKind(SyntaxKind.OpenBraceToken))
{
var text = await token.SyntaxTree!.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!token.IsFirstTokenOnLine(text))
{
return true;
}
}
return false;
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
char typedChar,
int caretPosition,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
// first, find the token user just typed.
var token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (token.IsMissing ||
!ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) ||
token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingRules = GetFormattingRules(document, caretPosition, token);
var service = document.GetLanguageService<ISyntaxFactsService>();
if (service != null && service.IsInNonUserCode(token.SyntaxTree, caretPosition, cancellationToken))
{
return ImmutableArray<TextChange>.Empty;
}
var shouldNotFormat = await TokenShouldNotFormatOnTypeCharAsync(token, cancellationToken).ConfigureAwait(false);
if (shouldNotFormat)
{
return ImmutableArray<TextChange>.Empty;
}
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Do not attempt to format on open/close brace if autoformat on close brace feature is
// off, instead just smart indent.
//
// We want this behavior because it's totally reasonable for a user to want to not have
// on automatic formatting because they feel it is too aggressive. However, by default,
// if you have smart-indentation on and are just hitting enter, you'll common have the
// caret placed one indent higher than your current construct. For example, if you have:
//
// if (true)
// $ <-- smart indent will have placed the caret here here.
//
// This is acceptable given that the user may want to just write a simple statement there.
// However, if they start writing `{`, then things should snap over to be:
//
// if (true)
// {
//
// Importantly, this is just an indentation change, no actual 'formatting' is done. We do
// the same with close brace. If you have:
//
// if (...)
// {
// bad . ly ( for (mmated+code) ) ;
// $ <-- smart indent will have placed the care here.
//
// If the user hits `}` then we will properly smart indent the `}` to match the `{`.
// However, we won't touch any of the other code in that block, unlike if we were
// formatting.
var onlySmartIndent =
(token.IsKind(SyntaxKind.CloseBraceToken) && OnlySmartIndentCloseBrace(options)) ||
(token.IsKind(SyntaxKind.OpenBraceToken) && OnlySmartIndentOpenBrace(options));
if (onlySmartIndent)
{
// if we're only doing smart indent, then ignore all edits to this token that occur before
// the span of the token. They're irrelevant and may screw up other code the user doesn't
// want touched.
var tokenEdits = await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
return tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToImmutableArray();
}
// if formatting range fails, do format token one at least
var changes = await FormatRangeAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
if (changes.Length > 0)
{
return changes;
}
return (await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false)).ToImmutableArray();
}
private static bool OnlySmartIndentCloseBrace(DocumentOptionSet options)
{
// User does not want auto-formatting (either in general, or for close braces in
// specific). So we only smart indent close braces when typed.
return !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace) ||
!options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static bool OnlySmartIndentOpenBrace(DocumentOptionSet options)
{
// User does not want auto-formatting . So we only smart indent open braces when typed.
// Note: there is no specific option for controlling formatting on open brace. So we
// don't have the symmetry with OnlySmartIndentCloseBrace.
return !options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static async Task<SyntaxToken> GetTokenBeforeTheCaretAsync(Document document, int caretPosition, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var position = Math.Max(0, caretPosition - 1);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position, findInsideTrivia: true);
return token;
}
private static async Task<IList<TextChange>> FormatTokenAsync(Document document, OptionSet options, SyntaxToken token, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = CreateSmartTokenFormatter(options, formattingRules, root);
var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false);
return changes;
}
private static ISmartTokenFormatter CreateSmartTokenFormatter(OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode root)
=> new CSharpSmartTokenFormatter(optionSet, formattingRules, (CompilationUnitSyntax)root);
private static async Task<ImmutableArray<TextChange>> FormatRangeAsync(
Document document,
OptionSet options,
SyntaxToken endToken,
IEnumerable<AbstractFormattingRule> formattingRules,
CancellationToken cancellationToken)
{
if (!IsEndToken(endToken))
{
return ImmutableArray<TextChange>.Empty;
}
var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);
if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)root);
var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken);
return changes.ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetTypingRules(SyntaxToken tokenBeforeCaret)
{
// Typing introduces several challenges around formatting.
// Historically we've shipped several triggers that cause formatting to happen directly while typing.
// These include formatting of blocks when '}' is typed, formatting of statements when a ';' is typed, formatting of ```case```s when ':' typed, and many other cases.
// However, formatting during typing can potentially cause problems. This is because the surrounding code may not be complete,
// or may otherwise have syntax errors, and thus edits could have unintended consequences.
//
// Because of this, we introduce an extra rule into the set of formatting rules whose purpose is to actually make formatting *more*
// conservative and *less* willing willing to make edits to the tree.
// The primary effect this rule has is to assume that more code is on a single line (and thus should stay that way)
// despite what the tree actually looks like.
//
// It's ok that this is only during formatting that is caused by an edit because that formatting happens
// implicitly and thus has to be more careful, whereas an explicit format-document call only happens on-demand
// and can be more aggressive about what it's doing.
//
//
// For example, say you have the following code.
//
// ```c#
// class C
// {
// int P { get { return
// }
// ```
//
// Hitting ';' after 'return' should ideally only affect the 'return statement' and change it to:
//
// ```c#
// class C
// {
// int P { get { return;
// }
// ```
//
// During a normal format-document call, this is not what would happen.
// Specifically, because the parser will consume the '}' into the accessor,
// it will think the accessor spans multiple lines, and thus should not stay on a single line. This will produce:
//
// ```c#
// class C
// {
// int P
// {
// get
// {
// return;
// }
// ```
//
// Because it's ok for this to format in that fashion if format-document is invoked,
// but should not happen during typing, we insert a specialized rule *only* during typing to try to control this.
// During normal formatting we add 'keep on single line' suppression rules for blocks we find that are on a single line.
// But that won't work since this span is not on a single line:
//
// ```c#
// class C
// {
// int P { get [|{ return;
// }|]
// ```
//
// So, during typing, if we see any parent block is incomplete, we'll assume that
// all our parent blocks are incomplete and we will place the suppression span like so:
//
// ```c#
// class C
// {
// int P { get [|{ return;|]
// }
// ```
//
// This will have the desired effect of keeping these tokens on the same line, but only during typing scenarios.
if (tokenBeforeCaret.Kind() == SyntaxKind.CloseBraceToken ||
tokenBeforeCaret.Kind() == SyntaxKind.EndOfFileToken)
{
return SpecializedCollections.EmptyEnumerable<AbstractFormattingRule>();
}
return SpecializedCollections.SingletonEnumerable(TypingFormattingRule.Instance);
}
private static bool IsEndToken(SyntaxToken endToken)
{
if (endToken.IsKind(SyntaxKind.OpenBraceToken))
{
return false;
}
return true;
}
// We'll autoformat on n, t, e, only if they are the last character of the below
// keywords.
private static bool ValidSingleOrMultiCharactersTokenKind(char typedChar, SyntaxKind kind)
=> typedChar switch
{
'n' => kind == SyntaxKind.RegionKeyword || kind == SyntaxKind.EndRegionKeyword,
't' => kind == SyntaxKind.SelectKeyword,
'e' => kind == SyntaxKind.WhereKeyword,
_ => true,
};
private static bool IsInvalidTokenKind(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Indentation;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
[ExportLanguageService(typeof(IFormattingInteractionService), LanguageNames.CSharp), Shared]
internal partial class CSharpFormattingInteractionService : IFormattingInteractionService
{
// All the characters that might potentially trigger formatting when typed
private readonly char[] _supportedChars = ";{}#nte:)".ToCharArray();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpFormattingInteractionService()
{
}
public bool SupportsFormatDocument => true;
public bool SupportsFormatOnPaste => true;
public bool SupportsFormatSelection => true;
public bool SupportsFormatOnReturn => false;
public bool SupportsFormattingOnTypedCharacter(Document document, char ch)
{
// Performance: This method checks several options to determine if we should do smart
// indent, none of which are controlled by editorconfig. Instead of calling
// document.GetOptionsAsync we can use the Workspace's global options and thus save the
// work of attempting to read in the editorconfig file.
var options = document.Project.Solution.Workspace.Options;
var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) == FormattingOptions.IndentStyle.Smart;
// We consider the proper placement of a close curly or open curly when it is typed at
// the start of the line to be a smart-indentation operation. As such, even if "format
// on typing" is off, if "smart indent" is on, we'll still format this. (However, we
// won't touch anything else in the block this close curly belongs to.).
//
// See extended comment in GetFormattingChangesAsync for more details on this.
if (smartIndentOn)
{
if (ch == '{' || ch == '}')
{
return true;
}
}
// If format-on-typing is not on, then we don't support formatting on any other characters.
var autoFormattingOnTyping = options.GetOption(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp);
if (!autoFormattingOnTyping)
{
return false;
}
if (ch == '}' && !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp))
{
return false;
}
if (ch == ';' && !options.GetOption(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp))
{
return false;
}
// don't auto format after these keys if smart indenting is not on.
if ((ch == '#' || ch == 'n') && !smartIndentOn)
{
return false;
}
return _supportedChars.Contains(ch);
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
TextSpan? textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var span = textSpan ?? new TextSpan(0, root.FullSpan.Length);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, span);
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: true, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root,
SpecializedCollections.SingletonEnumerable(formattingSpan),
document.Project.Solution.Workspace, options, cancellationToken).ToImmutableArray();
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync(
Document document,
TextSpan textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan);
var service = document.GetLanguageService<ISyntaxFormattingService>();
if (service == null)
{
return ImmutableArray<TextChange>.Empty;
}
var rules = new List<AbstractFormattingRule>() { new PasteFormattingRule() };
rules.AddRange(service.GetDefaultFormattingRules());
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, rules, cancellationToken).ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, SyntaxToken tokenBeforeCaret)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
return formattingRuleFactory.CreateRule(document, position).Concat(GetTypingRules(tokenBeforeCaret)).Concat(Formatter.GetDefaultFormattingRules(document));
}
Task<ImmutableArray<TextChange>> IFormattingInteractionService.GetFormattingChangesOnReturnAsync(
Document document, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken)
=> SpecializedTasks.EmptyImmutableArray<TextChange>();
private static async Task<bool> TokenShouldNotFormatOnTypeCharAsync(
SyntaxToken token, CancellationToken cancellationToken)
{
// If the token is a ) we only want to format if it's the close paren
// of a using statement. That way if we have nested usings, the inner
// using will align with the outer one when the user types the close paren.
if (token.IsKind(SyntaxKind.CloseParenToken) && !token.Parent.IsKind(SyntaxKind.UsingStatement))
{
return true;
}
// If the token is a : we only want to format if it's a labeled statement
// or case. When the colon is typed we'll want ot immediately have those
// statements snap to their appropriate indentation level.
if (token.IsKind(SyntaxKind.ColonToken) && !(token.Parent.IsKind(SyntaxKind.LabeledStatement) || token.Parent is SwitchLabelSyntax))
{
return true;
}
// Only format an { if it is the first token on a line. We don't want to
// mess with it if it's inside a line.
if (token.IsKind(SyntaxKind.OpenBraceToken))
{
var text = await token.SyntaxTree!.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!token.IsFirstTokenOnLine(text))
{
return true;
}
}
return false;
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
char typedChar,
int caretPosition,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
// first, find the token user just typed.
var token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (token.IsMissing ||
!ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) ||
token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingRules = GetFormattingRules(document, caretPosition, token);
var service = document.GetLanguageService<ISyntaxFactsService>();
if (service != null && service.IsInNonUserCode(token.SyntaxTree, caretPosition, cancellationToken))
{
return ImmutableArray<TextChange>.Empty;
}
var shouldNotFormat = await TokenShouldNotFormatOnTypeCharAsync(token, cancellationToken).ConfigureAwait(false);
if (shouldNotFormat)
{
return ImmutableArray<TextChange>.Empty;
}
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Do not attempt to format on open/close brace if autoformat on close brace feature is
// off, instead just smart indent.
//
// We want this behavior because it's totally reasonable for a user to want to not have
// on automatic formatting because they feel it is too aggressive. However, by default,
// if you have smart-indentation on and are just hitting enter, you'll common have the
// caret placed one indent higher than your current construct. For example, if you have:
//
// if (true)
// $ <-- smart indent will have placed the caret here here.
//
// This is acceptable given that the user may want to just write a simple statement there.
// However, if they start writing `{`, then things should snap over to be:
//
// if (true)
// {
//
// Importantly, this is just an indentation change, no actual 'formatting' is done. We do
// the same with close brace. If you have:
//
// if (...)
// {
// bad . ly ( for (mmated+code) ) ;
// $ <-- smart indent will have placed the care here.
//
// If the user hits `}` then we will properly smart indent the `}` to match the `{`.
// However, we won't touch any of the other code in that block, unlike if we were
// formatting.
var onlySmartIndent =
(token.IsKind(SyntaxKind.CloseBraceToken) && OnlySmartIndentCloseBrace(options)) ||
(token.IsKind(SyntaxKind.OpenBraceToken) && OnlySmartIndentOpenBrace(options));
if (onlySmartIndent)
{
// if we're only doing smart indent, then ignore all edits to this token that occur before
// the span of the token. They're irrelevant and may screw up other code the user doesn't
// want touched.
var tokenEdits = await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
return tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToImmutableArray();
}
// if formatting range fails, do format token one at least
var changes = await FormatRangeAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
if (changes.Length > 0)
{
return changes;
}
return (await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false)).ToImmutableArray();
}
private static bool OnlySmartIndentCloseBrace(DocumentOptionSet options)
{
// User does not want auto-formatting (either in general, or for close braces in
// specific). So we only smart indent close braces when typed.
return !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace) ||
!options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static bool OnlySmartIndentOpenBrace(DocumentOptionSet options)
{
// User does not want auto-formatting . So we only smart indent open braces when typed.
// Note: there is no specific option for controlling formatting on open brace. So we
// don't have the symmetry with OnlySmartIndentCloseBrace.
return !options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static async Task<SyntaxToken> GetTokenBeforeTheCaretAsync(Document document, int caretPosition, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var position = Math.Max(0, caretPosition - 1);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position, findInsideTrivia: true);
return token;
}
private static async Task<IList<TextChange>> FormatTokenAsync(Document document, OptionSet options, SyntaxToken token, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = CreateSmartTokenFormatter(options, formattingRules, root);
var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false);
return changes;
}
private static ISmartTokenFormatter CreateSmartTokenFormatter(OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode root)
=> new CSharpSmartTokenFormatter(optionSet, formattingRules, (CompilationUnitSyntax)root);
private static async Task<ImmutableArray<TextChange>> FormatRangeAsync(
Document document,
OptionSet options,
SyntaxToken endToken,
IEnumerable<AbstractFormattingRule> formattingRules,
CancellationToken cancellationToken)
{
if (!IsEndToken(endToken))
{
return ImmutableArray<TextChange>.Empty;
}
var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);
if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)root);
var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken);
return changes.ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetTypingRules(SyntaxToken tokenBeforeCaret)
{
// Typing introduces several challenges around formatting.
// Historically we've shipped several triggers that cause formatting to happen directly while typing.
// These include formatting of blocks when '}' is typed, formatting of statements when a ';' is typed, formatting of ```case```s when ':' typed, and many other cases.
// However, formatting during typing can potentially cause problems. This is because the surrounding code may not be complete,
// or may otherwise have syntax errors, and thus edits could have unintended consequences.
//
// Because of this, we introduce an extra rule into the set of formatting rules whose purpose is to actually make formatting *more*
// conservative and *less* willing willing to make edits to the tree.
// The primary effect this rule has is to assume that more code is on a single line (and thus should stay that way)
// despite what the tree actually looks like.
//
// It's ok that this is only during formatting that is caused by an edit because that formatting happens
// implicitly and thus has to be more careful, whereas an explicit format-document call only happens on-demand
// and can be more aggressive about what it's doing.
//
//
// For example, say you have the following code.
//
// ```c#
// class C
// {
// int P { get { return
// }
// ```
//
// Hitting ';' after 'return' should ideally only affect the 'return statement' and change it to:
//
// ```c#
// class C
// {
// int P { get { return;
// }
// ```
//
// During a normal format-document call, this is not what would happen.
// Specifically, because the parser will consume the '}' into the accessor,
// it will think the accessor spans multiple lines, and thus should not stay on a single line. This will produce:
//
// ```c#
// class C
// {
// int P
// {
// get
// {
// return;
// }
// ```
//
// Because it's ok for this to format in that fashion if format-document is invoked,
// but should not happen during typing, we insert a specialized rule *only* during typing to try to control this.
// During normal formatting we add 'keep on single line' suppression rules for blocks we find that are on a single line.
// But that won't work since this span is not on a single line:
//
// ```c#
// class C
// {
// int P { get [|{ return;
// }|]
// ```
//
// So, during typing, if we see any parent block is incomplete, we'll assume that
// all our parent blocks are incomplete and we will place the suppression span like so:
//
// ```c#
// class C
// {
// int P { get [|{ return;|]
// }
// ```
//
// This will have the desired effect of keeping these tokens on the same line, but only during typing scenarios.
if (tokenBeforeCaret.Kind() == SyntaxKind.CloseBraceToken ||
tokenBeforeCaret.Kind() == SyntaxKind.EndOfFileToken)
{
return SpecializedCollections.EmptyEnumerable<AbstractFormattingRule>();
}
return SpecializedCollections.SingletonEnumerable(TypingFormattingRule.Instance);
}
private static bool IsEndToken(SyntaxToken endToken)
{
if (endToken.IsKind(SyntaxKind.OpenBraceToken))
{
return false;
}
return true;
}
// We'll autoformat on n, t, e, only if they are the last character of the below
// keywords.
private static bool ValidSingleOrMultiCharactersTokenKind(char typedChar, SyntaxKind kind)
=> typedChar switch
{
'n' => kind == SyntaxKind.RegionKeyword || kind == SyntaxKind.EndRegionKeyword,
't' => kind == SyntaxKind.SelectKeyword,
'e' => kind == SyntaxKind.WhereKeyword,
_ => true,
};
private static bool IsInvalidTokenKind(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/CodeFixes/CodeFix.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Represents a single fix. This is essentially a tuple
/// that holds on to a <see cref="CodeAction"/> and the set of
/// <see cref="Diagnostic"/>s that this <see cref="CodeAction"/> will fix.
/// </summary>
internal sealed class CodeFix
{
internal readonly Project Project;
internal readonly CodeAction Action;
internal readonly ImmutableArray<Diagnostic> Diagnostics;
/// <summary>
/// This is the diagnostic that will show up in the preview pane header when a particular fix
/// is selected in the light bulb menu. We also group all fixes with the same <see cref="PrimaryDiagnostic"/>
/// together (into a single SuggestedActionSet) in the light bulb menu.
/// </summary>
/// <remarks>
/// A given fix can fix one or more diagnostics. However, our light bulb UI (preview pane, grouping
/// of fixes in the light bulb menu etc.) currently keeps things simple and pretends that
/// each fix fixes a single <see cref="PrimaryDiagnostic"/>.
///
/// Implementation-wise the <see cref="PrimaryDiagnostic"/> is always the first diagnostic that
/// the <see cref="CodeFixProvider"/> supplied when registering the fix (<see
/// cref="CodeFixContext.RegisterCodeFix(CodeAction, IEnumerable{Diagnostic})"/>). This could change
/// in the future, if we decide to change the UI to depict the true mapping between fixes and diagnostics
/// or if we decide to use some other heuristic to determine the <see cref="PrimaryDiagnostic"/>.
/// </remarks>
internal Diagnostic PrimaryDiagnostic => Diagnostics[0];
internal CodeFix(Project project, CodeAction action, Diagnostic diagnostic)
{
Project = project;
Action = action;
Diagnostics = ImmutableArray.Create(diagnostic);
}
internal CodeFix(Project project, CodeAction action, ImmutableArray<Diagnostic> diagnostics)
{
Debug.Assert(!diagnostics.IsDefaultOrEmpty);
Project = project;
Action = action;
Diagnostics = diagnostics;
}
internal DiagnosticData GetPrimaryDiagnosticData()
{
var diagnostic = PrimaryDiagnostic;
if (diagnostic.Location.IsInSource)
{
var document = Project.GetDocument(diagnostic.Location.SourceTree);
if (document != null)
{
return DiagnosticData.Create(diagnostic, document);
}
}
else if (diagnostic.Location.Kind == LocationKind.ExternalFile)
{
var document = Project.Documents.FirstOrDefault(d => d.FilePath == diagnostic.Location.GetLineSpan().Path);
if (document != null)
{
return DiagnosticData.Create(diagnostic, document);
}
}
return DiagnosticData.Create(diagnostic, Project);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Represents a single fix. This is essentially a tuple
/// that holds on to a <see cref="CodeAction"/> and the set of
/// <see cref="Diagnostic"/>s that this <see cref="CodeAction"/> will fix.
/// </summary>
internal sealed class CodeFix
{
internal readonly Project Project;
internal readonly CodeAction Action;
internal readonly ImmutableArray<Diagnostic> Diagnostics;
/// <summary>
/// This is the diagnostic that will show up in the preview pane header when a particular fix
/// is selected in the light bulb menu. We also group all fixes with the same <see cref="PrimaryDiagnostic"/>
/// together (into a single SuggestedActionSet) in the light bulb menu.
/// </summary>
/// <remarks>
/// A given fix can fix one or more diagnostics. However, our light bulb UI (preview pane, grouping
/// of fixes in the light bulb menu etc.) currently keeps things simple and pretends that
/// each fix fixes a single <see cref="PrimaryDiagnostic"/>.
///
/// Implementation-wise the <see cref="PrimaryDiagnostic"/> is always the first diagnostic that
/// the <see cref="CodeFixProvider"/> supplied when registering the fix (<see
/// cref="CodeFixContext.RegisterCodeFix(CodeAction, IEnumerable{Diagnostic})"/>). This could change
/// in the future, if we decide to change the UI to depict the true mapping between fixes and diagnostics
/// or if we decide to use some other heuristic to determine the <see cref="PrimaryDiagnostic"/>.
/// </remarks>
internal Diagnostic PrimaryDiagnostic => Diagnostics[0];
internal CodeFix(Project project, CodeAction action, Diagnostic diagnostic)
{
Project = project;
Action = action;
Diagnostics = ImmutableArray.Create(diagnostic);
}
internal CodeFix(Project project, CodeAction action, ImmutableArray<Diagnostic> diagnostics)
{
Debug.Assert(!diagnostics.IsDefaultOrEmpty);
Project = project;
Action = action;
Diagnostics = diagnostics;
}
internal DiagnosticData GetPrimaryDiagnosticData()
{
var diagnostic = PrimaryDiagnostic;
if (diagnostic.Location.IsInSource)
{
var document = Project.GetDocument(diagnostic.Location.SourceTree);
if (document != null)
{
return DiagnosticData.Create(diagnostic, document);
}
}
else if (diagnostic.Location.Kind == LocationKind.ExternalFile)
{
var document = Project.Documents.FirstOrDefault(d => d.FilePath == diagnostic.Location.GetLineSpan().Path);
if (document != null)
{
return DiagnosticData.Create(diagnostic, document);
}
}
return DiagnosticData.Create(diagnostic, Project);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/SourceGeneration/Nodes/TransformNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
namespace Microsoft.CodeAnalysis
{
internal sealed class TransformNode<TInput, TOutput> : IIncrementalGeneratorNode<TOutput>
{
private readonly Func<TInput, CancellationToken, ImmutableArray<TOutput>> _func;
private readonly IEqualityComparer<TOutput> _comparer;
private readonly IIncrementalGeneratorNode<TInput> _sourceNode;
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, TOutput> userFunc, IEqualityComparer<TOutput>? comparer = null)
: this(sourceNode, userFunc: (i, token) => ImmutableArray.Create(userFunc(i, token)), comparer)
{
}
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, ImmutableArray<TOutput>> userFunc, IEqualityComparer<TOutput>? comparer = null)
{
_sourceNode = sourceNode;
_func = userFunc;
_comparer = comparer ?? EqualityComparer<TOutput>.Default;
}
public IIncrementalGeneratorNode<TOutput> WithComparer(IEqualityComparer<TOutput> comparer) => new TransformNode<TInput, TOutput>(_sourceNode, _func, comparer);
public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken)
{
// grab the source inputs
var sourceTable = builder.GetLatestStateTableForNode(_sourceNode);
if (sourceTable.IsCached)
{
return previousTable;
}
// Semantics of a transform:
// Element-wise comparison of upstream table
// - Cached or Removed: no transform, just use previous values
// - Added: perform transform and add
// - Modified: perform transform and do element wise comparison with previous results
var newTable = previousTable.ToBuilder();
foreach (var entry in sourceTable)
{
if (entry.state == EntryState.Removed)
{
newTable.RemoveEntries();
}
else if (entry.state != EntryState.Cached || !newTable.TryUseCachedEntries())
{
// generate the new entries
var newOutputs = _func(entry.item, cancellationToken);
if (entry.state != EntryState.Modified || !newTable.TryModifyEntries(newOutputs, _comparer))
{
newTable.AddEntries(newOutputs, EntryState.Added);
}
}
}
return newTable.ToImmutableAndFree();
}
public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
namespace Microsoft.CodeAnalysis
{
internal sealed class TransformNode<TInput, TOutput> : IIncrementalGeneratorNode<TOutput>
{
private readonly Func<TInput, CancellationToken, ImmutableArray<TOutput>> _func;
private readonly IEqualityComparer<TOutput> _comparer;
private readonly IIncrementalGeneratorNode<TInput> _sourceNode;
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, TOutput> userFunc, IEqualityComparer<TOutput>? comparer = null)
: this(sourceNode, userFunc: (i, token) => ImmutableArray.Create(userFunc(i, token)), comparer)
{
}
public TransformNode(IIncrementalGeneratorNode<TInput> sourceNode, Func<TInput, CancellationToken, ImmutableArray<TOutput>> userFunc, IEqualityComparer<TOutput>? comparer = null)
{
_sourceNode = sourceNode;
_func = userFunc;
_comparer = comparer ?? EqualityComparer<TOutput>.Default;
}
public IIncrementalGeneratorNode<TOutput> WithComparer(IEqualityComparer<TOutput> comparer) => new TransformNode<TInput, TOutput>(_sourceNode, _func, comparer);
public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken)
{
// grab the source inputs
var sourceTable = builder.GetLatestStateTableForNode(_sourceNode);
if (sourceTable.IsCached)
{
return previousTable;
}
// Semantics of a transform:
// Element-wise comparison of upstream table
// - Cached or Removed: no transform, just use previous values
// - Added: perform transform and add
// - Modified: perform transform and do element wise comparison with previous results
var newTable = previousTable.ToBuilder();
foreach (var entry in sourceTable)
{
if (entry.state == EntryState.Removed)
{
newTable.RemoveEntries();
}
else if (entry.state != EntryState.Cached || !newTable.TryUseCachedEntries())
{
// generate the new entries
var newOutputs = _func(entry.item, cancellationToken);
if (entry.state != EntryState.Modified || !newTable.TryModifyEntries(newOutputs, _comparer))
{
newTable.AddEntries(newOutputs, EntryState.Added);
}
}
}
return newTable.ToImmutableAndFree();
}
public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output);
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableHashMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Contract = System.Diagnostics.Contracts.Contract;
namespace Roslyn.Collections.Immutable
{
/// <summary>
/// An immutable unordered hash map implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableHashMap<,>.DebuggerProxy))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
internal sealed class ImmutableHashMap<TKey, TValue> : IImmutableDictionary<TKey, TValue>
where TKey : notnull
{
private static readonly ImmutableHashMap<TKey, TValue> s_emptySingleton = new();
/// <summary>
/// The root node of the tree that stores this map.
/// </summary>
private readonly Bucket? _root;
/// <summary>
/// The comparer used to sort keys in this map.
/// </summary>
private readonly IEqualityComparer<TKey> _keyComparer;
/// <summary>
/// The comparer used to detect equivalent values in this map.
/// </summary>
private readonly IEqualityComparer<TValue> _valueComparer;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>"/> class.
/// </summary>
/// <param name="root">The root.</param>
/// <param name="comparer">The comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
private ImmutableHashMap(Bucket? root, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer)
: this(comparer, valueComparer)
{
RoslynDebug.AssertNotNull(comparer);
RoslynDebug.AssertNotNull(valueComparer);
_root = root;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>"/> class.
/// </summary>
/// <param name="comparer">The comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
internal ImmutableHashMap(IEqualityComparer<TKey>? comparer = null, IEqualityComparer<TValue>? valueComparer = null)
{
_keyComparer = comparer ?? EqualityComparer<TKey>.Default;
_valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
}
/// <summary>
/// Gets an empty map with default equality comparers.
/// </summary>
public static ImmutableHashMap<TKey, TValue> Empty => s_emptySingleton;
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public ImmutableHashMap<TKey, TValue> Clear()
=> this.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer);
#region Public methods
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key));
if (_root == null)
{
return this.Wrap(vb);
}
else
{
return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, false));
}
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
Requires.NotNull(pairs, "pairs");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
return this.AddRange(pairs, overwriteOnCollision: false, avoidToHashMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
Contract.Ensures(!Contract.Result<ImmutableHashMap<TKey, TValue>>().IsEmpty);
var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key));
if (_root == null)
{
return this.Wrap(vb);
}
else
{
return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, true));
}
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
[Pure]
public ImmutableHashMap<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, "items");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return this.AddRange(items, overwriteOnCollision: true, avoidToHashMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> Remove(TKey key)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
if (_root != null)
{
return this.Wrap(_root.Remove(_keyComparer.GetHashCode(key), key, _keyComparer));
}
return this;
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
var map = _root;
if (map != null)
{
foreach (var key in keys)
{
map = map.Remove(_keyComparer.GetHashCode(key), key, _keyComparer);
if (map == null)
{
break;
}
}
}
return this.Wrap(map);
}
/// <summary>
/// Returns a hash map that uses the specified key and value comparers and has the same contents as this map.
/// </summary>
/// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param>
/// <param name="valueComparer">The value comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param>
/// <returns>The hash map with the new comparers.</returns>
/// <remarks>
/// In the event that a change in the key equality comparer results in a key collision, an exception is thrown.
/// </remarks>
[Pure]
public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
if (keyComparer == null)
{
keyComparer = EqualityComparer<TKey>.Default;
}
if (valueComparer == null)
{
valueComparer = EqualityComparer<TValue>.Default;
}
if (_keyComparer == keyComparer)
{
if (_valueComparer == valueComparer)
{
return this;
}
else
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
return new ImmutableHashMap<TKey, TValue>(_root, _keyComparer, valueComparer);
}
}
else
{
var set = new ImmutableHashMap<TKey, TValue>(keyComparer, valueComparer);
set = set.AddRange(this, overwriteOnCollision: false, avoidToHashMap: true);
return set;
}
}
/// <summary>
/// Returns a hash map that uses the specified key comparer and current value comparer and has the same contents as this map.
/// </summary>
/// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param>
/// <returns>The hash map with the new comparers.</returns>
/// <remarks>
/// In the event that a change in the key equality comparer results in a key collision, an exception is thrown.
/// </remarks>
[Pure]
public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer)
=> this.WithComparers(keyComparer, _valueComparer);
/// <summary>
/// Determines whether the ImmutableSortedMap<TKey,TValue>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the ImmutableSortedMap<TKey,TValue>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the ImmutableSortedMap<TKey,TValue> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
=> this.Values.Contains(value, _valueComparer);
#endregion
#region IImmutableDictionary<TKey, TValue> Members
/// <summary>
/// Gets the number of elements in this collection.
/// </summary>
public int Count
{
get { return _root != null ? _root.Count : 0; }
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return this.Count == 0; }
}
/// <summary>
/// Gets the keys in the map.
/// </summary>
public IEnumerable<TKey> Keys
{
get
{
if (_root == null)
{
yield break;
}
var stack = new Stack<IEnumerator<Bucket>>();
stack.Push(_root.GetAll().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Peek();
if (en.MoveNext())
{
if (en.Current is ValueBucket vb)
{
yield return vb.Key;
}
else
{
stack.Push(en.Current.GetAll().GetEnumerator());
}
}
else
{
stack.Pop();
}
}
}
}
/// <summary>
/// Gets the values in the map.
/// </summary>
public IEnumerable<TValue> Values
{
#pragma warning disable 618
get { return this.GetValueBuckets().Select(vb => vb.Value); }
#pragma warning restore 618
}
/// <summary>
/// Gets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
public TValue this[TKey key]
{
get
{
if (this.TryGetValue(key, out var value))
{
return value;
}
throw new KeyNotFoundException();
}
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(TKey key)
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer);
return vb != null;
}
return false;
}
/// <summary>
/// Determines whether this map contains the specified key-value pair.
/// </summary>
/// <param name="keyValuePair">The key value pair.</param>
/// <returns>
/// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(keyValuePair.Key), keyValuePair.Key, _keyComparer);
return vb != null && _valueComparer.Equals(vb.Value, keyValuePair.Value);
}
return false;
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer);
if (vb != null)
{
value = vb.Value;
return true;
}
}
value = default;
return false;
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(equalKey), equalKey, _keyComparer);
if (vb != null)
{
actualKey = vb.Key;
return true;
}
}
actualKey = equalKey;
return false;
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
=> this.GetValueBuckets().Select(vb => new KeyValuePair<TKey, TValue>(vb.Key, vb.Value)).GetEnumerator();
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
#endregion
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
var builder = new StringBuilder("ImmutableHashMap[");
var needComma = false;
foreach (var kv in this)
{
builder.Append(kv.Key);
builder.Append(":");
builder.Append(kv.Value);
if (needComma)
{
builder.Append(",");
}
needComma = true;
}
builder.Append("]");
return builder.ToString();
}
/// <summary>
/// Exchanges a key for the actual key instance found in this map.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="existingKey">Receives the equal key found in the map.</param>
/// <returns>A value indicating whether an equal and existing key was found in the map.</returns>
internal bool TryExchangeKey(TKey key, [NotNullWhen(true)] out TKey? existingKey)
{
var vb = _root != null ? _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer) : null;
if (vb != null)
{
existingKey = vb.Key;
return true;
}
else
{
existingKey = default;
return false;
}
}
/// <summary>
/// Attempts to discover an <see cref="ImmutableHashMap<TKey, TValue>"/> instance beneath some enumerable sequence
/// if one exists.
/// </summary>
/// <param name="sequence">The sequence that may have come from an immutable map.</param>
/// <param name="other">Receives the concrete <see cref="ImmutableHashMap<TKey, TValue>"/> typed value if one can be found.</param>
/// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns>
private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, [NotNullWhen(true)] out ImmutableHashMap<TKey, TValue>? other)
{
other = sequence as ImmutableHashMap<TKey, TValue>;
if (other != null)
{
return true;
}
return false;
}
private ImmutableHashMap<TKey, TValue> Wrap(Bucket? root)
{
if (root == null)
{
return this.Clear();
}
if (_root != root)
{
return root.Count == 0 ? this.Clear() : new ImmutableHashMap<TKey, TValue>(root, _keyComparer, _valueComparer);
}
return this;
}
/// <summary>
/// Bulk adds entries to the map.
/// </summary>
/// <param name="pairs">The entries to add.</param>
/// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="pairs"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param>
/// <param name="avoidToHashMap"><c>true</c> when being called from ToHashMap to avoid StackOverflow.</param>
[Pure]
private ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool overwriteOnCollision, bool avoidToHashMap)
{
RoslynDebug.AssertNotNull(pairs);
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
// Some optimizations may apply if we're an empty list.
if (this.IsEmpty && !avoidToHashMap)
{
// If the items being added actually come from an ImmutableHashMap<TKey, TValue>
// then there is no value in reconstructing it.
if (TryCastToImmutableMap(pairs, out var other))
{
return other.WithComparers(_keyComparer, _valueComparer);
}
}
var map = this;
foreach (var pair in pairs)
{
map = overwriteOnCollision
? map.SetItem(pair.Key, pair.Value)
: map.Add(pair.Key, pair.Value);
}
return map;
}
private IEnumerable<ValueBucket> GetValueBuckets()
{
if (_root == null)
{
yield break;
}
var stack = new Stack<IEnumerator<Bucket>>();
stack.Push(_root.GetAll().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Peek();
if (en.MoveNext())
{
if (en.Current is ValueBucket vb)
{
yield return vb;
}
else
{
stack.Push(en.Current.GetAll().GetEnumerator());
}
}
else
{
stack.Pop();
}
}
}
private abstract class Bucket
{
internal abstract int Count { get; }
internal abstract Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue);
internal abstract Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer);
internal abstract ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer);
internal abstract IEnumerable<Bucket> GetAll();
}
private abstract class ValueOrListBucket : Bucket
{
/// <summary>
/// The hash for this bucket.
/// </summary>
internal readonly int Hash;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.ValueOrListBucket"/> class.
/// </summary>
/// <param name="hash">The hash.</param>
protected ValueOrListBucket(int hash)
=> this.Hash = hash;
}
private sealed class ValueBucket : ValueOrListBucket
{
internal readonly TKey Key;
internal readonly TValue Value;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.ValueBucket"/> class.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="hashcode">The hashcode.</param>
internal ValueBucket(TKey key, TValue value, int hashcode)
: base(hashcode)
{
this.Key = key;
this.Value = value;
}
internal override int Count => 1;
internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue)
{
if (this.Hash == bucket.Hash)
{
if (comparer.Equals(this.Key, bucket.Key))
{
// Overwrite of same key. If the value is the same as well, don't switch out the bucket.
if (valueComparer.Equals(this.Value, bucket.Value))
{
return this;
}
else
{
if (overwriteExistingValue)
{
return bucket;
}
else
{
throw new ArgumentException(Strings.DuplicateKey);
}
}
}
else
{
// two of the same hash will never be happy in a hash bucket
return new ListBucket(new ValueBucket[] { this, bucket });
}
}
else
{
return new HashBucket(suggestedHashRoll, this, bucket);
}
}
internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash && comparer.Equals(this.Key, key))
{
return null;
}
return this;
}
internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash && comparer.Equals(this.Key, key))
{
return this;
}
return null;
}
internal override IEnumerable<Bucket> GetAll()
=> SpecializedCollections.SingletonEnumerable(this);
}
private sealed class ListBucket : ValueOrListBucket
{
private readonly ValueBucket[] _buckets;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.ListBucket"/> class.
/// </summary>
/// <param name="buckets">The buckets.</param>
internal ListBucket(ValueBucket[] buckets)
: base(buckets[0].Hash)
{
RoslynDebug.AssertNotNull(buckets);
Debug.Assert(buckets.Length >= 2);
_buckets = buckets;
}
internal override int Count => _buckets.Length;
internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue)
{
if (this.Hash == bucket.Hash)
{
var pos = this.Find(bucket.Key, comparer);
if (pos >= 0)
{
// If the value hasn't changed for this key, return the original bucket.
if (valueComparer.Equals(bucket.Value, _buckets[pos].Value))
{
return this;
}
else
{
if (overwriteExistingValue)
{
return new ListBucket(_buckets.ReplaceAt(pos, bucket));
}
else
{
throw new ArgumentException(Strings.DuplicateKey);
}
}
}
else
{
return new ListBucket(_buckets.InsertAt(_buckets.Length, bucket));
}
}
else
{
return new HashBucket(suggestedHashRoll, this, bucket);
}
}
internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash)
{
var pos = this.Find(key, comparer);
if (pos >= 0)
{
if (_buckets.Length == 1)
{
return null;
}
else if (_buckets.Length == 2)
{
return pos == 0 ? _buckets[1] : _buckets[0];
}
else
{
return new ListBucket(_buckets.RemoveAt(pos));
}
}
}
return this;
}
internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash)
{
var pos = this.Find(key, comparer);
if (pos >= 0)
{
return _buckets[pos];
}
}
return null;
}
private int Find(TKey key, IEqualityComparer<TKey> comparer)
{
for (var i = 0; i < _buckets.Length; i++)
{
if (comparer.Equals(key, _buckets[i].Key))
{
return i;
}
}
return -1;
}
internal override IEnumerable<Bucket> GetAll()
=> _buckets;
}
private sealed class HashBucket : Bucket
{
private readonly int _hashRoll;
private readonly uint _used;
private readonly Bucket[] _buckets;
private readonly int _count;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.HashBucket"/> class.
/// </summary>
/// <param name="hashRoll">The hash roll.</param>
/// <param name="used">The used.</param>
/// <param name="buckets">The buckets.</param>
/// <param name="count">The count.</param>
private HashBucket(int hashRoll, uint used, Bucket[] buckets, int count)
{
RoslynDebug.AssertNotNull(buckets);
Debug.Assert(buckets.Length == CountBits(used));
_hashRoll = hashRoll & 31;
_used = used;
_buckets = buckets;
_count = count;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.HashBucket"/> class.
/// </summary>
/// <param name="suggestedHashRoll">The suggested hash roll.</param>
/// <param name="bucket1">The bucket1.</param>
/// <param name="bucket2">The bucket2.</param>
internal HashBucket(int suggestedHashRoll, ValueOrListBucket bucket1, ValueOrListBucket bucket2)
{
RoslynDebug.AssertNotNull(bucket1);
RoslynDebug.AssertNotNull(bucket2);
Debug.Assert(bucket1.Hash != bucket2.Hash);
// find next hashRoll that causes these two to be slotted in different buckets
var h1 = bucket1.Hash;
var h2 = bucket2.Hash;
int s1;
int s2;
for (var i = 0; i < 32; i++)
{
_hashRoll = (suggestedHashRoll + i) & 31;
s1 = this.ComputeLogicalSlot(h1);
s2 = this.ComputeLogicalSlot(h2);
if (s1 != s2)
{
_count = 2;
_used = (1u << s1) | (1u << s2);
_buckets = new Bucket[2];
_buckets[this.ComputePhysicalSlot(s1)] = bucket1;
_buckets[this.ComputePhysicalSlot(s2)] = bucket2;
return;
}
}
throw new InvalidOperationException();
}
internal override int Count => _count;
internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue)
{
var logicalSlot = ComputeLogicalSlot(bucket.Hash);
if (IsInUse(logicalSlot))
{
// if this slot is in use, then add the new item to the one in this slot
var physicalSlot = ComputePhysicalSlot(logicalSlot);
var existing = _buckets[physicalSlot];
// suggest hash roll that will cause any nested hash bucket to use entirely new bits for picking logical slot
// note: we ignore passed in suggestion, and base new suggestion off current hash roll.
var added = existing.Add(_hashRoll + 5, bucket, keyComparer, valueComparer, overwriteExistingValue);
if (added != existing)
{
var newBuckets = _buckets.ReplaceAt(physicalSlot, added);
return new HashBucket(_hashRoll, _used, newBuckets, _count - existing.Count + added.Count);
}
else
{
return this;
}
}
else
{
var physicalSlot = ComputePhysicalSlot(logicalSlot);
var newBuckets = _buckets.InsertAt(physicalSlot, bucket);
var newUsed = InsertBit(logicalSlot, _used);
return new HashBucket(_hashRoll, newUsed, newBuckets, _count + bucket.Count);
}
}
internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
var logicalSlot = ComputeLogicalSlot(hash);
if (IsInUse(logicalSlot))
{
var physicalSlot = ComputePhysicalSlot(logicalSlot);
var existing = _buckets[physicalSlot];
var result = existing.Remove(hash, key, comparer);
if (result == null)
{
if (_buckets.Length == 1)
{
return null;
}
else if (_buckets.Length == 2)
{
return physicalSlot == 0 ? _buckets[1] : _buckets[0];
}
else
{
return new HashBucket(_hashRoll, RemoveBit(logicalSlot, _used), _buckets.RemoveAt(physicalSlot), _count - existing.Count);
}
}
else if (_buckets[physicalSlot] != result)
{
return new HashBucket(_hashRoll, _used, _buckets.ReplaceAt(physicalSlot, result), _count - existing.Count + result.Count);
}
}
return this;
}
internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
var logicalSlot = ComputeLogicalSlot(hash);
if (IsInUse(logicalSlot))
{
var physicalSlot = ComputePhysicalSlot(logicalSlot);
return _buckets[physicalSlot].Get(hash, key, comparer);
}
return null;
}
internal override IEnumerable<Bucket> GetAll()
=> _buckets;
private bool IsInUse(int logicalSlot)
=> ((1 << logicalSlot) & _used) != 0;
private int ComputeLogicalSlot(int hc)
{
var uc = unchecked((uint)hc);
var rotated = RotateRight(uc, _hashRoll);
return unchecked((int)(rotated & 31));
}
[Pure]
private static uint RotateRight(uint v, int n)
{
Debug.Assert(n >= 0 && n < 32);
if (n == 0)
{
return v;
}
return v >> n | (v << (32 - n));
}
private int ComputePhysicalSlot(int logicalSlot)
{
Debug.Assert(logicalSlot >= 0 && logicalSlot < 32);
Contract.Ensures(Contract.Result<int>() >= 0);
if (_buckets.Length == 32)
{
return logicalSlot;
}
if (logicalSlot == 0)
{
return 0;
}
var mask = uint.MaxValue >> (32 - logicalSlot); // only count the bits up to the logical slot #
return CountBits(_used & mask);
}
[Pure]
private static int CountBits(uint v)
{
unchecked
{
v -= ((v >> 1) & 0x55555555u);
v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u);
return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24;
}
}
[Pure]
private static uint InsertBit(int position, uint bits)
{
Debug.Assert(0 == (bits & (1u << position)));
return bits | (1u << position);
}
[Pure]
private static uint RemoveBit(int position, uint bits)
{
Debug.Assert(0 != (bits & (1u << position)));
return bits & ~(1u << position);
}
}
#region IImmutableDictionary<TKey,TValue> Members
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
=> this.Clear();
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> this.Add(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
=> this.SetItem(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
=> this.SetItems(items);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
=> this.AddRange(pairs);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
=> this.RemoveRange(keys);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key)
=> this.Remove(key);
#endregion
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
private class DebuggerProxy
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableHashMap<TKey, TValue> _map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[]? _contents;
/// <summary>
/// Initializes a new instance of the <see cref="DebuggerProxy"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public DebuggerProxy(ImmutableHashMap<TKey, TValue> map)
{
Requires.NotNull(map, "map");
_map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (_contents == null)
{
_contents = _map.ToArray();
}
return _contents;
}
}
}
private static class Requires
{
[DebuggerStepThrough]
public static T NotNullAllowStructs<T>(T value, string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
[DebuggerStepThrough]
public static T NotNull<T>(T value, string parameterName) where T : class
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
[DebuggerStepThrough]
public static Exception FailRange(string parameterName, string? message = null)
{
if (string.IsNullOrEmpty(message))
{
throw new ArgumentOutOfRangeException(parameterName);
}
throw new ArgumentOutOfRangeException(parameterName, message);
}
[DebuggerStepThrough]
public static void Range(bool condition, string parameterName, string? message = null)
{
if (!condition)
{
Requires.FailRange(parameterName, message);
}
}
}
private static class Strings
{
public static string DuplicateKey => CompilerExtensionsResources.An_element_with_the_same_key_but_a_different_value_already_exists;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Contract = System.Diagnostics.Contracts.Contract;
namespace Roslyn.Collections.Immutable
{
/// <summary>
/// An immutable unordered hash map implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableHashMap<,>.DebuggerProxy))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
internal sealed class ImmutableHashMap<TKey, TValue> : IImmutableDictionary<TKey, TValue>
where TKey : notnull
{
private static readonly ImmutableHashMap<TKey, TValue> s_emptySingleton = new();
/// <summary>
/// The root node of the tree that stores this map.
/// </summary>
private readonly Bucket? _root;
/// <summary>
/// The comparer used to sort keys in this map.
/// </summary>
private readonly IEqualityComparer<TKey> _keyComparer;
/// <summary>
/// The comparer used to detect equivalent values in this map.
/// </summary>
private readonly IEqualityComparer<TValue> _valueComparer;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>"/> class.
/// </summary>
/// <param name="root">The root.</param>
/// <param name="comparer">The comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
private ImmutableHashMap(Bucket? root, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer)
: this(comparer, valueComparer)
{
RoslynDebug.AssertNotNull(comparer);
RoslynDebug.AssertNotNull(valueComparer);
_root = root;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>"/> class.
/// </summary>
/// <param name="comparer">The comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
internal ImmutableHashMap(IEqualityComparer<TKey>? comparer = null, IEqualityComparer<TValue>? valueComparer = null)
{
_keyComparer = comparer ?? EqualityComparer<TKey>.Default;
_valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
}
/// <summary>
/// Gets an empty map with default equality comparers.
/// </summary>
public static ImmutableHashMap<TKey, TValue> Empty => s_emptySingleton;
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public ImmutableHashMap<TKey, TValue> Clear()
=> this.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer);
#region Public methods
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key));
if (_root == null)
{
return this.Wrap(vb);
}
else
{
return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, false));
}
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
Requires.NotNull(pairs, "pairs");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
return this.AddRange(pairs, overwriteOnCollision: false, avoidToHashMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
Contract.Ensures(!Contract.Result<ImmutableHashMap<TKey, TValue>>().IsEmpty);
var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key));
if (_root == null)
{
return this.Wrap(vb);
}
else
{
return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, true));
}
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
[Pure]
public ImmutableHashMap<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, "items");
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return this.AddRange(items, overwriteOnCollision: true, avoidToHashMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> Remove(TKey key)
{
Requires.NotNullAllowStructs(key, "key");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
if (_root != null)
{
return this.Wrap(_root.Remove(_keyComparer.GetHashCode(key), key, _keyComparer));
}
return this;
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
[Pure]
public ImmutableHashMap<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
var map = _root;
if (map != null)
{
foreach (var key in keys)
{
map = map.Remove(_keyComparer.GetHashCode(key), key, _keyComparer);
if (map == null)
{
break;
}
}
}
return this.Wrap(map);
}
/// <summary>
/// Returns a hash map that uses the specified key and value comparers and has the same contents as this map.
/// </summary>
/// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param>
/// <param name="valueComparer">The value comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param>
/// <returns>The hash map with the new comparers.</returns>
/// <remarks>
/// In the event that a change in the key equality comparer results in a key collision, an exception is thrown.
/// </remarks>
[Pure]
public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
if (keyComparer == null)
{
keyComparer = EqualityComparer<TKey>.Default;
}
if (valueComparer == null)
{
valueComparer = EqualityComparer<TValue>.Default;
}
if (_keyComparer == keyComparer)
{
if (_valueComparer == valueComparer)
{
return this;
}
else
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
return new ImmutableHashMap<TKey, TValue>(_root, _keyComparer, valueComparer);
}
}
else
{
var set = new ImmutableHashMap<TKey, TValue>(keyComparer, valueComparer);
set = set.AddRange(this, overwriteOnCollision: false, avoidToHashMap: true);
return set;
}
}
/// <summary>
/// Returns a hash map that uses the specified key comparer and current value comparer and has the same contents as this map.
/// </summary>
/// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param>
/// <returns>The hash map with the new comparers.</returns>
/// <remarks>
/// In the event that a change in the key equality comparer results in a key collision, an exception is thrown.
/// </remarks>
[Pure]
public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer)
=> this.WithComparers(keyComparer, _valueComparer);
/// <summary>
/// Determines whether the ImmutableSortedMap<TKey,TValue>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the ImmutableSortedMap<TKey,TValue>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the ImmutableSortedMap<TKey,TValue> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
=> this.Values.Contains(value, _valueComparer);
#endregion
#region IImmutableDictionary<TKey, TValue> Members
/// <summary>
/// Gets the number of elements in this collection.
/// </summary>
public int Count
{
get { return _root != null ? _root.Count : 0; }
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return this.Count == 0; }
}
/// <summary>
/// Gets the keys in the map.
/// </summary>
public IEnumerable<TKey> Keys
{
get
{
if (_root == null)
{
yield break;
}
var stack = new Stack<IEnumerator<Bucket>>();
stack.Push(_root.GetAll().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Peek();
if (en.MoveNext())
{
if (en.Current is ValueBucket vb)
{
yield return vb.Key;
}
else
{
stack.Push(en.Current.GetAll().GetEnumerator());
}
}
else
{
stack.Pop();
}
}
}
}
/// <summary>
/// Gets the values in the map.
/// </summary>
public IEnumerable<TValue> Values
{
#pragma warning disable 618
get { return this.GetValueBuckets().Select(vb => vb.Value); }
#pragma warning restore 618
}
/// <summary>
/// Gets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
public TValue this[TKey key]
{
get
{
if (this.TryGetValue(key, out var value))
{
return value;
}
throw new KeyNotFoundException();
}
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(TKey key)
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer);
return vb != null;
}
return false;
}
/// <summary>
/// Determines whether this map contains the specified key-value pair.
/// </summary>
/// <param name="keyValuePair">The key value pair.</param>
/// <returns>
/// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(keyValuePair.Key), keyValuePair.Key, _keyComparer);
return vb != null && _valueComparer.Equals(vb.Value, keyValuePair.Value);
}
return false;
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer);
if (vb != null)
{
value = vb.Value;
return true;
}
}
value = default;
return false;
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
if (_root != null)
{
var vb = _root.Get(_keyComparer.GetHashCode(equalKey), equalKey, _keyComparer);
if (vb != null)
{
actualKey = vb.Key;
return true;
}
}
actualKey = equalKey;
return false;
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
=> this.GetValueBuckets().Select(vb => new KeyValuePair<TKey, TValue>(vb.Key, vb.Value)).GetEnumerator();
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
#endregion
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
var builder = new StringBuilder("ImmutableHashMap[");
var needComma = false;
foreach (var kv in this)
{
builder.Append(kv.Key);
builder.Append(":");
builder.Append(kv.Value);
if (needComma)
{
builder.Append(",");
}
needComma = true;
}
builder.Append("]");
return builder.ToString();
}
/// <summary>
/// Exchanges a key for the actual key instance found in this map.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="existingKey">Receives the equal key found in the map.</param>
/// <returns>A value indicating whether an equal and existing key was found in the map.</returns>
internal bool TryExchangeKey(TKey key, [NotNullWhen(true)] out TKey? existingKey)
{
var vb = _root != null ? _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer) : null;
if (vb != null)
{
existingKey = vb.Key;
return true;
}
else
{
existingKey = default;
return false;
}
}
/// <summary>
/// Attempts to discover an <see cref="ImmutableHashMap<TKey, TValue>"/> instance beneath some enumerable sequence
/// if one exists.
/// </summary>
/// <param name="sequence">The sequence that may have come from an immutable map.</param>
/// <param name="other">Receives the concrete <see cref="ImmutableHashMap<TKey, TValue>"/> typed value if one can be found.</param>
/// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns>
private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, [NotNullWhen(true)] out ImmutableHashMap<TKey, TValue>? other)
{
other = sequence as ImmutableHashMap<TKey, TValue>;
if (other != null)
{
return true;
}
return false;
}
private ImmutableHashMap<TKey, TValue> Wrap(Bucket? root)
{
if (root == null)
{
return this.Clear();
}
if (_root != root)
{
return root.Count == 0 ? this.Clear() : new ImmutableHashMap<TKey, TValue>(root, _keyComparer, _valueComparer);
}
return this;
}
/// <summary>
/// Bulk adds entries to the map.
/// </summary>
/// <param name="pairs">The entries to add.</param>
/// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="pairs"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param>
/// <param name="avoidToHashMap"><c>true</c> when being called from ToHashMap to avoid StackOverflow.</param>
[Pure]
private ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool overwriteOnCollision, bool avoidToHashMap)
{
RoslynDebug.AssertNotNull(pairs);
Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null);
// Some optimizations may apply if we're an empty list.
if (this.IsEmpty && !avoidToHashMap)
{
// If the items being added actually come from an ImmutableHashMap<TKey, TValue>
// then there is no value in reconstructing it.
if (TryCastToImmutableMap(pairs, out var other))
{
return other.WithComparers(_keyComparer, _valueComparer);
}
}
var map = this;
foreach (var pair in pairs)
{
map = overwriteOnCollision
? map.SetItem(pair.Key, pair.Value)
: map.Add(pair.Key, pair.Value);
}
return map;
}
private IEnumerable<ValueBucket> GetValueBuckets()
{
if (_root == null)
{
yield break;
}
var stack = new Stack<IEnumerator<Bucket>>();
stack.Push(_root.GetAll().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Peek();
if (en.MoveNext())
{
if (en.Current is ValueBucket vb)
{
yield return vb;
}
else
{
stack.Push(en.Current.GetAll().GetEnumerator());
}
}
else
{
stack.Pop();
}
}
}
private abstract class Bucket
{
internal abstract int Count { get; }
internal abstract Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue);
internal abstract Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer);
internal abstract ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer);
internal abstract IEnumerable<Bucket> GetAll();
}
private abstract class ValueOrListBucket : Bucket
{
/// <summary>
/// The hash for this bucket.
/// </summary>
internal readonly int Hash;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.ValueOrListBucket"/> class.
/// </summary>
/// <param name="hash">The hash.</param>
protected ValueOrListBucket(int hash)
=> this.Hash = hash;
}
private sealed class ValueBucket : ValueOrListBucket
{
internal readonly TKey Key;
internal readonly TValue Value;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.ValueBucket"/> class.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="hashcode">The hashcode.</param>
internal ValueBucket(TKey key, TValue value, int hashcode)
: base(hashcode)
{
this.Key = key;
this.Value = value;
}
internal override int Count => 1;
internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue)
{
if (this.Hash == bucket.Hash)
{
if (comparer.Equals(this.Key, bucket.Key))
{
// Overwrite of same key. If the value is the same as well, don't switch out the bucket.
if (valueComparer.Equals(this.Value, bucket.Value))
{
return this;
}
else
{
if (overwriteExistingValue)
{
return bucket;
}
else
{
throw new ArgumentException(Strings.DuplicateKey);
}
}
}
else
{
// two of the same hash will never be happy in a hash bucket
return new ListBucket(new ValueBucket[] { this, bucket });
}
}
else
{
return new HashBucket(suggestedHashRoll, this, bucket);
}
}
internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash && comparer.Equals(this.Key, key))
{
return null;
}
return this;
}
internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash && comparer.Equals(this.Key, key))
{
return this;
}
return null;
}
internal override IEnumerable<Bucket> GetAll()
=> SpecializedCollections.SingletonEnumerable(this);
}
private sealed class ListBucket : ValueOrListBucket
{
private readonly ValueBucket[] _buckets;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.ListBucket"/> class.
/// </summary>
/// <param name="buckets">The buckets.</param>
internal ListBucket(ValueBucket[] buckets)
: base(buckets[0].Hash)
{
RoslynDebug.AssertNotNull(buckets);
Debug.Assert(buckets.Length >= 2);
_buckets = buckets;
}
internal override int Count => _buckets.Length;
internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue)
{
if (this.Hash == bucket.Hash)
{
var pos = this.Find(bucket.Key, comparer);
if (pos >= 0)
{
// If the value hasn't changed for this key, return the original bucket.
if (valueComparer.Equals(bucket.Value, _buckets[pos].Value))
{
return this;
}
else
{
if (overwriteExistingValue)
{
return new ListBucket(_buckets.ReplaceAt(pos, bucket));
}
else
{
throw new ArgumentException(Strings.DuplicateKey);
}
}
}
else
{
return new ListBucket(_buckets.InsertAt(_buckets.Length, bucket));
}
}
else
{
return new HashBucket(suggestedHashRoll, this, bucket);
}
}
internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash)
{
var pos = this.Find(key, comparer);
if (pos >= 0)
{
if (_buckets.Length == 1)
{
return null;
}
else if (_buckets.Length == 2)
{
return pos == 0 ? _buckets[1] : _buckets[0];
}
else
{
return new ListBucket(_buckets.RemoveAt(pos));
}
}
}
return this;
}
internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
if (this.Hash == hash)
{
var pos = this.Find(key, comparer);
if (pos >= 0)
{
return _buckets[pos];
}
}
return null;
}
private int Find(TKey key, IEqualityComparer<TKey> comparer)
{
for (var i = 0; i < _buckets.Length; i++)
{
if (comparer.Equals(key, _buckets[i].Key))
{
return i;
}
}
return -1;
}
internal override IEnumerable<Bucket> GetAll()
=> _buckets;
}
private sealed class HashBucket : Bucket
{
private readonly int _hashRoll;
private readonly uint _used;
private readonly Bucket[] _buckets;
private readonly int _count;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.HashBucket"/> class.
/// </summary>
/// <param name="hashRoll">The hash roll.</param>
/// <param name="used">The used.</param>
/// <param name="buckets">The buckets.</param>
/// <param name="count">The count.</param>
private HashBucket(int hashRoll, uint used, Bucket[] buckets, int count)
{
RoslynDebug.AssertNotNull(buckets);
Debug.Assert(buckets.Length == CountBits(used));
_hashRoll = hashRoll & 31;
_used = used;
_buckets = buckets;
_count = count;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashMap<TKey, TValue>.HashBucket"/> class.
/// </summary>
/// <param name="suggestedHashRoll">The suggested hash roll.</param>
/// <param name="bucket1">The bucket1.</param>
/// <param name="bucket2">The bucket2.</param>
internal HashBucket(int suggestedHashRoll, ValueOrListBucket bucket1, ValueOrListBucket bucket2)
{
RoslynDebug.AssertNotNull(bucket1);
RoslynDebug.AssertNotNull(bucket2);
Debug.Assert(bucket1.Hash != bucket2.Hash);
// find next hashRoll that causes these two to be slotted in different buckets
var h1 = bucket1.Hash;
var h2 = bucket2.Hash;
int s1;
int s2;
for (var i = 0; i < 32; i++)
{
_hashRoll = (suggestedHashRoll + i) & 31;
s1 = this.ComputeLogicalSlot(h1);
s2 = this.ComputeLogicalSlot(h2);
if (s1 != s2)
{
_count = 2;
_used = (1u << s1) | (1u << s2);
_buckets = new Bucket[2];
_buckets[this.ComputePhysicalSlot(s1)] = bucket1;
_buckets[this.ComputePhysicalSlot(s2)] = bucket2;
return;
}
}
throw new InvalidOperationException();
}
internal override int Count => _count;
internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue)
{
var logicalSlot = ComputeLogicalSlot(bucket.Hash);
if (IsInUse(logicalSlot))
{
// if this slot is in use, then add the new item to the one in this slot
var physicalSlot = ComputePhysicalSlot(logicalSlot);
var existing = _buckets[physicalSlot];
// suggest hash roll that will cause any nested hash bucket to use entirely new bits for picking logical slot
// note: we ignore passed in suggestion, and base new suggestion off current hash roll.
var added = existing.Add(_hashRoll + 5, bucket, keyComparer, valueComparer, overwriteExistingValue);
if (added != existing)
{
var newBuckets = _buckets.ReplaceAt(physicalSlot, added);
return new HashBucket(_hashRoll, _used, newBuckets, _count - existing.Count + added.Count);
}
else
{
return this;
}
}
else
{
var physicalSlot = ComputePhysicalSlot(logicalSlot);
var newBuckets = _buckets.InsertAt(physicalSlot, bucket);
var newUsed = InsertBit(logicalSlot, _used);
return new HashBucket(_hashRoll, newUsed, newBuckets, _count + bucket.Count);
}
}
internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
var logicalSlot = ComputeLogicalSlot(hash);
if (IsInUse(logicalSlot))
{
var physicalSlot = ComputePhysicalSlot(logicalSlot);
var existing = _buckets[physicalSlot];
var result = existing.Remove(hash, key, comparer);
if (result == null)
{
if (_buckets.Length == 1)
{
return null;
}
else if (_buckets.Length == 2)
{
return physicalSlot == 0 ? _buckets[1] : _buckets[0];
}
else
{
return new HashBucket(_hashRoll, RemoveBit(logicalSlot, _used), _buckets.RemoveAt(physicalSlot), _count - existing.Count);
}
}
else if (_buckets[physicalSlot] != result)
{
return new HashBucket(_hashRoll, _used, _buckets.ReplaceAt(physicalSlot, result), _count - existing.Count + result.Count);
}
}
return this;
}
internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer)
{
var logicalSlot = ComputeLogicalSlot(hash);
if (IsInUse(logicalSlot))
{
var physicalSlot = ComputePhysicalSlot(logicalSlot);
return _buckets[physicalSlot].Get(hash, key, comparer);
}
return null;
}
internal override IEnumerable<Bucket> GetAll()
=> _buckets;
private bool IsInUse(int logicalSlot)
=> ((1 << logicalSlot) & _used) != 0;
private int ComputeLogicalSlot(int hc)
{
var uc = unchecked((uint)hc);
var rotated = RotateRight(uc, _hashRoll);
return unchecked((int)(rotated & 31));
}
[Pure]
private static uint RotateRight(uint v, int n)
{
Debug.Assert(n >= 0 && n < 32);
if (n == 0)
{
return v;
}
return v >> n | (v << (32 - n));
}
private int ComputePhysicalSlot(int logicalSlot)
{
Debug.Assert(logicalSlot >= 0 && logicalSlot < 32);
Contract.Ensures(Contract.Result<int>() >= 0);
if (_buckets.Length == 32)
{
return logicalSlot;
}
if (logicalSlot == 0)
{
return 0;
}
var mask = uint.MaxValue >> (32 - logicalSlot); // only count the bits up to the logical slot #
return CountBits(_used & mask);
}
[Pure]
private static int CountBits(uint v)
{
unchecked
{
v -= ((v >> 1) & 0x55555555u);
v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u);
return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24;
}
}
[Pure]
private static uint InsertBit(int position, uint bits)
{
Debug.Assert(0 == (bits & (1u << position)));
return bits | (1u << position);
}
[Pure]
private static uint RemoveBit(int position, uint bits)
{
Debug.Assert(0 != (bits & (1u << position)));
return bits & ~(1u << position);
}
}
#region IImmutableDictionary<TKey,TValue> Members
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
=> this.Clear();
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> this.Add(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
=> this.SetItem(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
=> this.SetItems(items);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
=> this.AddRange(pairs);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
=> this.RemoveRange(keys);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key)
=> this.Remove(key);
#endregion
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
private class DebuggerProxy
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableHashMap<TKey, TValue> _map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[]? _contents;
/// <summary>
/// Initializes a new instance of the <see cref="DebuggerProxy"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public DebuggerProxy(ImmutableHashMap<TKey, TValue> map)
{
Requires.NotNull(map, "map");
_map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (_contents == null)
{
_contents = _map.ToArray();
}
return _contents;
}
}
}
private static class Requires
{
[DebuggerStepThrough]
public static T NotNullAllowStructs<T>(T value, string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
[DebuggerStepThrough]
public static T NotNull<T>(T value, string parameterName) where T : class
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
[DebuggerStepThrough]
public static Exception FailRange(string parameterName, string? message = null)
{
if (string.IsNullOrEmpty(message))
{
throw new ArgumentOutOfRangeException(parameterName);
}
throw new ArgumentOutOfRangeException(parameterName, message);
}
[DebuggerStepThrough]
public static void Range(bool condition, string parameterName, string? message = null)
{
if (!condition)
{
Requires.FailRange(parameterName, message);
}
}
}
private static class Strings
{
public static string DuplicateKey => CompilerExtensionsResources.An_element_with_the_same_key_but_a_different_value_already_exists;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Test/PdbUtilities/Writer/SymWriterTestUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.DiaSymReader;
namespace Roslyn.Test.PdbUtilities
{
internal static class SymWriterTestUtilities
{
public static readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> ThrowingFactory =
_ => throw new SymUnmanagedWriterException("xxx", new NotSupportedException(), "<lib name>");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.DiaSymReader;
namespace Roslyn.Test.PdbUtilities
{
internal static class SymWriterTestUtilities
{
public static readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> ThrowingFactory =
_ => throw new SymUnmanagedWriterException("xxx", new NotSupportedException(), "<lib name>");
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
using static System.Linq.ImmutableArrayExtensions;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal partial class CodeGenerator
{
private int _recursionDepth;
private class EmitCancelledException : Exception
{ }
private enum UseKind
{
Unused,
UsedAsValue,
UsedAsAddress
}
private void EmitExpression(BoundExpression expression, bool used)
{
if (expression == null)
{
return;
}
var constantValue = expression.ConstantValue;
if (constantValue != null)
{
if (!used)
{
// unused constants have no side-effects.
return;
}
if ((object)expression.Type == null || expression.Type.SpecialType != SpecialType.System_Decimal)
{
EmitConstantExpression(expression.Type, constantValue, used, expression.Syntax);
return;
}
}
_recursionDepth++;
if (_recursionDepth > 1)
{
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
EmitExpressionCore(expression, used);
}
else
{
EmitExpressionCoreWithStackGuard(expression, used);
}
_recursionDepth--;
}
private void EmitExpressionCoreWithStackGuard(BoundExpression expression, bool used)
{
Debug.Assert(_recursionDepth == 1);
try
{
EmitExpressionCore(expression, used);
Debug.Assert(_recursionDepth == 1);
}
catch (InsufficientExecutionStackException)
{
_diagnostics.Add(ErrorCode.ERR_InsufficientStack,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(expression));
throw new EmitCancelledException();
}
}
private void EmitExpressionCore(BoundExpression expression, bool used)
{
switch (expression.Kind)
{
case BoundKind.AssignmentOperator:
EmitAssignmentExpression((BoundAssignmentOperator)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.Call:
EmitCallExpression((BoundCall)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.ObjectCreationExpression:
EmitObjectCreationExpression((BoundObjectCreationExpression)expression, used);
break;
case BoundKind.DelegateCreationExpression:
EmitDelegateCreationExpression((BoundDelegateCreationExpression)expression, used);
break;
case BoundKind.ArrayCreation:
EmitArrayCreationExpression((BoundArrayCreation)expression, used);
break;
case BoundKind.ConvertedStackAllocExpression:
EmitConvertedStackAllocExpression((BoundConvertedStackAllocExpression)expression, used);
break;
case BoundKind.ReadOnlySpanFromArray:
EmitReadOnlySpanFromArrayExpression((BoundReadOnlySpanFromArray)expression, used);
break;
case BoundKind.Conversion:
EmitConversionExpression((BoundConversion)expression, used);
break;
case BoundKind.Local:
EmitLocalLoad((BoundLocal)expression, used);
break;
case BoundKind.Dup:
EmitDupExpression((BoundDup)expression, used);
break;
case BoundKind.PassByCopy:
EmitExpression(((BoundPassByCopy)expression).Expression, used);
break;
case BoundKind.Parameter:
if (used) // unused parameter has no side-effects
{
EmitParameterLoad((BoundParameter)expression);
}
break;
case BoundKind.FieldAccess:
EmitFieldLoad((BoundFieldAccess)expression, used);
break;
case BoundKind.ArrayAccess:
EmitArrayElementLoad((BoundArrayAccess)expression, used);
break;
case BoundKind.ArrayLength:
EmitArrayLength((BoundArrayLength)expression, used);
break;
case BoundKind.ThisReference:
if (used) // unused this has no side-effects
{
EmitThisReferenceExpression((BoundThisReference)expression);
}
break;
case BoundKind.PreviousSubmissionReference:
// Script references are lowered to a this reference and a field access.
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
case BoundKind.BaseReference:
if (used) // unused base has no side-effects
{
var thisType = _method.ContainingType;
_builder.EmitOpCode(ILOpCode.Ldarg_0);
if (thisType.IsValueType)
{
EmitLoadIndirect(thisType, expression.Syntax);
EmitBox(thisType, expression.Syntax);
}
}
break;
case BoundKind.Sequence:
EmitSequenceExpression((BoundSequence)expression, used);
break;
case BoundKind.SequencePointExpression:
EmitSequencePointExpression((BoundSequencePointExpression)expression, used);
break;
case BoundKind.UnaryOperator:
EmitUnaryOperatorExpression((BoundUnaryOperator)expression, used);
break;
case BoundKind.BinaryOperator:
EmitBinaryOperatorExpression((BoundBinaryOperator)expression, used);
break;
case BoundKind.NullCoalescingOperator:
EmitNullCoalescingOperator((BoundNullCoalescingOperator)expression, used);
break;
case BoundKind.IsOperator:
EmitIsExpression((BoundIsOperator)expression, used);
break;
case BoundKind.AsOperator:
EmitAsExpression((BoundAsOperator)expression, used);
break;
case BoundKind.DefaultExpression:
EmitDefaultExpression((BoundDefaultExpression)expression, used);
break;
case BoundKind.TypeOfOperator:
if (used) // unused typeof has no side-effects
{
EmitTypeOfExpression((BoundTypeOfOperator)expression);
}
break;
case BoundKind.SizeOfOperator:
if (used) // unused sizeof has no side-effects
{
EmitSizeOfExpression((BoundSizeOfOperator)expression);
}
break;
case BoundKind.ModuleVersionId:
Debug.Assert(used);
EmitModuleVersionIdLoad((BoundModuleVersionId)expression);
break;
case BoundKind.ModuleVersionIdString:
Debug.Assert(used);
EmitModuleVersionIdStringLoad((BoundModuleVersionIdString)expression);
break;
case BoundKind.InstrumentationPayloadRoot:
Debug.Assert(used);
EmitInstrumentationPayloadRootLoad((BoundInstrumentationPayloadRoot)expression);
break;
case BoundKind.MethodDefIndex:
Debug.Assert(used);
EmitMethodDefIndexExpression((BoundMethodDefIndex)expression);
break;
case BoundKind.MaximumMethodDefIndex:
Debug.Assert(used);
EmitMaximumMethodDefIndexExpression((BoundMaximumMethodDefIndex)expression);
break;
case BoundKind.SourceDocumentIndex:
Debug.Assert(used);
EmitSourceDocumentIndex((BoundSourceDocumentIndex)expression);
break;
case BoundKind.MethodInfo:
if (used)
{
EmitMethodInfoExpression((BoundMethodInfo)expression);
}
break;
case BoundKind.FieldInfo:
if (used)
{
EmitFieldInfoExpression((BoundFieldInfo)expression);
}
break;
case BoundKind.ConditionalOperator:
EmitConditionalOperator((BoundConditionalOperator)expression, used);
break;
case BoundKind.AddressOfOperator:
EmitAddressOfExpression((BoundAddressOfOperator)expression, used);
break;
case BoundKind.PointerIndirectionOperator:
EmitPointerIndirectionOperator((BoundPointerIndirectionOperator)expression, used);
break;
case BoundKind.ArgList:
EmitArgList(used);
break;
case BoundKind.ArgListOperator:
Debug.Assert(used);
EmitArgListOperator((BoundArgListOperator)expression);
break;
case BoundKind.RefTypeOperator:
EmitRefTypeOperator((BoundRefTypeOperator)expression, used);
break;
case BoundKind.MakeRefOperator:
EmitMakeRefOperator((BoundMakeRefOperator)expression, used);
break;
case BoundKind.RefValueOperator:
EmitRefValueOperator((BoundRefValueOperator)expression, used);
break;
case BoundKind.LoweredConditionalAccess:
EmitLoweredConditionalAccessExpression((BoundLoweredConditionalAccess)expression, used);
break;
case BoundKind.ConditionalReceiver:
EmitConditionalReceiver((BoundConditionalReceiver)expression, used);
break;
case BoundKind.ComplexConditionalReceiver:
EmitComplexConditionalReceiver((BoundComplexConditionalReceiver)expression, used);
break;
case BoundKind.PseudoVariable:
EmitPseudoVariableValue((BoundPseudoVariable)expression, used);
break;
case BoundKind.ThrowExpression:
EmitThrowExpression((BoundThrowExpression)expression, used);
break;
case BoundKind.FunctionPointerInvocation:
EmitCalli((BoundFunctionPointerInvocation)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.FunctionPointerLoad:
EmitLoadFunction((BoundFunctionPointerLoad)expression, used);
break;
default:
// Code gen should not be invoked if there are errors.
Debug.Assert(expression.Kind != BoundKind.BadExpression);
// node should have been lowered:
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
}
}
private void EmitThrowExpression(BoundThrowExpression node, bool used)
{
this.EmitThrow(node.Expression);
// to satisfy invariants, we push a default value to pretend to adjust the stack height
EmitDefaultValue(node.Type, used, node.Syntax);
}
private void EmitComplexConditionalReceiver(BoundComplexConditionalReceiver expression, bool used)
{
Debug.Assert(!expression.Type.IsReferenceType);
Debug.Assert(!expression.Type.IsValueType);
var receiverType = expression.Type;
var whenValueTypeLabel = new object();
var doneLabel = new object();
EmitInitObj(receiverType, true, expression.Syntax);
EmitBox(receiverType, expression.Syntax);
_builder.EmitBranch(ILOpCode.Brtrue, whenValueTypeLabel);
EmitExpression(expression.ReferenceTypeReceiver, used);
_builder.EmitBranch(ILOpCode.Br, doneLabel);
_builder.AdjustStack(-1);
_builder.MarkLabel(whenValueTypeLabel);
EmitExpression(expression.ValueTypeReceiver, used);
_builder.MarkLabel(doneLabel);
}
private void EmitLoweredConditionalAccessExpression(BoundLoweredConditionalAccess expression, bool used)
{
var receiver = expression.Receiver;
var receiverType = receiver.Type;
LocalDefinition receiverTemp = null;
Debug.Assert(!receiverType.IsValueType ||
(receiverType.IsNullableType() && expression.HasValueMethodOpt != null), "conditional receiver cannot be a struct");
var receiverConstant = receiver.ConstantValue;
if (receiverConstant?.IsNull == false)
{
// const but not null, must be a reference type
Debug.Assert(receiverType.IsVerifierReference());
// receiver is a reference type, so addresskind does not matter, but we do not intend to write.
receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
EmitExpression(expression.WhenNotNull, used);
if (receiverTemp != null)
{
FreeTemp(receiverTemp);
}
return;
}
// labels
object whenNotNullLabel = new object();
object doneLabel = new object();
LocalDefinition cloneTemp = null;
var notConstrained = !receiverType.IsReferenceType && !receiverType.IsValueType;
// we need a copy if we deal with nonlocal value (to capture the value)
// or if we have a ref-constrained T (to do box just once)
// or if we deal with stack local (reads are destructive)
// or if we have default(T) (to do box just once)
var nullCheckOnCopy = LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
(receiverType.IsReferenceType && receiverType.TypeKind == TypeKind.TypeParameter) ||
(receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol));
// ===== RECEIVER
if (nullCheckOnCopy)
{
if (notConstrained)
{
// if T happens to be a value type, it could be a target of mutating calls.
receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
if (receiverTemp is null)
{
// unconstrained case needs to handle case where T is actually a struct.
// such values are never nulls
// we will emit a check for such case, but the check is really a JIT-time
// constant since JIT will know if T is a struct or not.
// if ((object)default(T) != null)
// {
// goto whenNotNull
// }
// else
// {
// temp = receiverRef
// receiverRef = ref temp
// }
EmitDefaultValue(receiverType, true, receiver.Syntax);
EmitBox(receiverType, receiver.Syntax);
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
EmitLoadIndirect(receiverType, receiver.Syntax);
cloneTemp = AllocateTemp(receiverType, receiver.Syntax);
_builder.EmitLocalStore(cloneTemp);
_builder.EmitLocalAddress(cloneTemp);
_builder.EmitLocalLoad(cloneTemp);
EmitBox(receiverType, receiver.Syntax);
// here we have loaded a ref to a temp and its boxed value { &T, O }
}
else
{
// We are calling the expression on a copy of the target anyway,
// so even if T is a struct, we don't need to make sure we call the expression on the original target.
// We currently have an address on the stack. Duplicate it, and load the value of the address.
_builder.EmitOpCode(ILOpCode.Dup);
EmitLoadIndirect(receiverType, receiver.Syntax);
EmitBox(receiverType, receiver.Syntax);
}
}
else
{
// this does not need to be writeable
// we may call "HasValue" on this, but it is not mutating
var addressKind = AddressKind.ReadOnly;
receiverTemp = EmitReceiverRef(receiver, addressKind);
_builder.EmitOpCode(ILOpCode.Dup);
// here we have loaded two copies of a reference { O, O } or {&nub, &nub}
}
}
else
{
// this does not need to be writeable.
// we may call "HasValue" on this, but it is not mutating
// besides, since we are not making a copy, the receiver is not a field,
// so it cannot be readonly, in verifier sense, anyways.
receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
// here we have loaded just { O } or {&nub}
// we have the most trivial case where we can just reload receiver when needed again
}
// ===== CONDITION
var hasValueOpt = expression.HasValueMethodOpt;
if (hasValueOpt != null)
{
Debug.Assert(receiver.Type.IsNullableType());
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
EmitSymbolToken(hasValueOpt, expression.Syntax, null);
}
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
// no longer need the temp if we are not holding a copy
if (receiverTemp != null && !nullCheckOnCopy)
{
FreeTemp(receiverTemp);
receiverTemp = null;
}
// ===== WHEN NULL
if (nullCheckOnCopy)
{
_builder.EmitOpCode(ILOpCode.Pop);
}
var whenNull = expression.WhenNullOpt;
if (whenNull == null)
{
EmitDefaultValue(expression.Type, used, expression.Syntax);
}
else
{
EmitExpression(whenNull, used);
}
_builder.EmitBranch(ILOpCode.Br, doneLabel);
// ===== WHEN NOT NULL
if (nullCheckOnCopy)
{
// notNull branch pops copy of receiver off the stack when nullCheckOnCopy
// however on the isNull branch we still have the stack as it was and need
// to adjust stack depth correspondingly.
_builder.AdjustStack(+1);
}
if (used)
{
// notNull branch pushes default on the stack when used
// however on the isNull branch we still have the stack as it was and need
// to adjust stack depth correspondingly.
_builder.AdjustStack(-1);
}
_builder.MarkLabel(whenNotNullLabel);
if (!nullCheckOnCopy)
{
Debug.Assert(receiverTemp == null);
// receiver may be used as target of a struct call (if T happens to be a struct)
receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
Debug.Assert(receiverTemp == null || receiver.IsDefaultValue());
}
EmitExpression(expression.WhenNotNull, used);
// ===== DONE
_builder.MarkLabel(doneLabel);
if (cloneTemp != null)
{
FreeTemp(cloneTemp);
}
if (receiverTemp != null)
{
FreeTemp(receiverTemp);
}
}
private void EmitConditionalReceiver(BoundConditionalReceiver expression, bool used)
{
Debug.Assert(!expression.Type.IsValueType);
if (!expression.Type.IsReferenceType)
{
EmitLoadIndirect(expression.Type, expression.Syntax);
}
EmitPopIfUnused(used);
}
private void EmitRefValueOperator(BoundRefValueOperator expression, bool used)
{
EmitRefValueAddress(expression);
EmitLoadIndirect(expression.Type, expression.Syntax);
EmitPopIfUnused(used);
}
private void EmitMakeRefOperator(BoundMakeRefOperator expression, bool used)
{
// push address of variable
// mkrefany [Type] -- takes address off stack, puts TypedReference on stack
var temp = EmitAddress(expression.Operand, AddressKind.Writeable);
Debug.Assert(temp == null, "makeref should not create temps");
_builder.EmitOpCode(ILOpCode.Mkrefany);
EmitSymbolToken(expression.Operand.Type, expression.Operand.Syntax);
EmitPopIfUnused(used);
}
private void EmitRefTypeOperator(BoundRefTypeOperator expression, bool used)
{
// push TypedReference
// refanytype -- takes TypedReference off stack, puts token on stack
// call GetTypeFromHandle -- takes token off stack, puts Type on stack
EmitExpression(expression.Operand, true);
_builder.EmitOpCode(ILOpCode.Refanytype);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
var getTypeMethod = expression.GetTypeFromHandle;
Debug.Assert((object)getTypeMethod != null);
EmitSymbolToken(getTypeMethod, expression.Syntax, null);
EmitPopIfUnused(used);
}
private void EmitArgList(bool used)
{
_builder.EmitOpCode(ILOpCode.Arglist);
EmitPopIfUnused(used);
}
private void EmitArgListOperator(BoundArgListOperator expression)
{
for (int i = 0; i < expression.Arguments.Length; i++)
{
BoundExpression argument = expression.Arguments[i];
RefKind refKind = expression.ArgumentRefKindsOpt.IsDefaultOrEmpty ? RefKind.None : expression.ArgumentRefKindsOpt[i];
EmitArgument(argument, refKind);
}
}
private void EmitArgument(BoundExpression argument, RefKind refKind)
{
switch (refKind)
{
case RefKind.None:
EmitExpression(argument, true);
break;
case RefKind.In:
var temp = EmitAddress(argument, AddressKind.ReadOnly);
AddExpressionTemp(temp);
break;
default:
// NOTE: passing "ReadOnlyStrict" here.
// we should not get an address of a copy if at all possible
var unexpectedTemp = EmitAddress(argument, refKind == RefKindExtensions.StrictIn ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
if (unexpectedTemp != null)
{
// interestingly enough "ref dynamic" sometimes is passed via a clone
Debug.Assert(argument.Type.IsDynamic(), "passing args byref should not clone them into temps");
AddExpressionTemp(unexpectedTemp);
}
break;
}
}
private void EmitAddressOfExpression(BoundAddressOfOperator expression, bool used)
{
// NOTE: passing "ReadOnlyStrict" here.
// we should not get an address of a copy if at all possible
var temp = EmitAddress(expression.Operand, AddressKind.ReadOnlyStrict);
Debug.Assert(temp == null, "If the operand is addressable, then a temp shouldn't be required.");
if (used && !expression.IsManaged)
{
// When computing an address to be used to initialize a fixed-statement variable, we have to be careful
// not to convert the managed reference to an unmanaged pointer before storing it. Otherwise the GC might
// come along and move memory around, invalidating the pointer before it is pinned by being stored in
// the fixed variable. But elsewhere in the code we do use a conv.u instruction to convert the managed
// reference to the underlying type for unmanaged pointers, which is the type "unsigned int" (see CLI
// standard, Partition I section 12.1.1.1).
_builder.EmitOpCode(ILOpCode.Conv_u);
}
EmitPopIfUnused(used);
}
private void EmitPointerIndirectionOperator(BoundPointerIndirectionOperator expression, bool used)
{
EmitExpression(expression.Operand, used: true);
EmitLoadIndirect(expression.Type, expression.Syntax);
EmitPopIfUnused(used);
}
private void EmitDupExpression(BoundDup expression, bool used)
{
if (expression.RefKind == RefKind.None)
{
// unused dup is noop
if (used)
{
_builder.EmitOpCode(ILOpCode.Dup);
}
}
else
{
_builder.EmitOpCode(ILOpCode.Dup);
// must read in case if it is a null ref
EmitLoadIndirect(expression.Type, expression.Syntax);
EmitPopIfUnused(used);
}
}
private void EmitDelegateCreationExpression(BoundDelegateCreationExpression expression, bool used)
{
var mg = expression.Argument as BoundMethodGroup;
var receiver = mg != null ? mg.ReceiverOpt : expression.Argument;
var meth = expression.MethodOpt ?? receiver.Type.DelegateInvokeMethod();
Debug.Assert((object)meth != null);
EmitDelegateCreation(expression, receiver, expression.IsExtensionMethod, meth, expression.Type, used);
}
private void EmitThisReferenceExpression(BoundThisReference thisRef)
{
var thisType = thisRef.Type;
Debug.Assert(thisType.TypeKind != TypeKind.TypeParameter);
_builder.EmitOpCode(ILOpCode.Ldarg_0);
if (thisType.IsValueType)
{
EmitLoadIndirect(thisType, thisRef.Syntax);
}
}
private void EmitPseudoVariableValue(BoundPseudoVariable expression, bool used)
{
EmitExpression(expression.EmitExpressions.GetValue(expression, _diagnostics), used);
}
private void EmitSequencePointExpression(BoundSequencePointExpression node, bool used)
{
EmitSequencePoint(node);
// used is true to ensure that something is emitted
EmitExpression(node.Expression, used: true);
EmitPopIfUnused(used);
}
private void EmitSequencePoint(BoundSequencePointExpression node)
{
var syntax = node.Syntax;
if (_emitPdbSequencePoints)
{
if (syntax == null)
{
EmitHiddenSequencePoint();
}
else
{
EmitSequencePoint(syntax);
}
}
}
private void EmitSequenceExpression(BoundSequence sequence, bool used)
{
DefineLocals(sequence);
EmitSideEffects(sequence);
// CONSIDER: LocalRewriter.RewriteNestedObjectOrCollectionInitializerExpression may create a bound sequence with an unused BoundTypeExpression as the value,
// CONSIDER: which must be ignored by codegen. See comments in RewriteNestedObjectOrCollectionInitializerExpression for details and an example.
// CONSIDER: We may want to instead consider making the Value field of BoundSequence node optional to allow a sequence with
// CONSIDER: only side effects and no value. Note that VB's BoundSequence node has an optional value field.
// CONSIDER: This will allow us to remove the below check before emitting the value.
Debug.Assert(sequence.Value.Kind != BoundKind.TypeExpression || !used);
if (sequence.Value.Kind != BoundKind.TypeExpression)
{
EmitExpression(sequence.Value, used);
}
// sequence is used as a value, can release all locals
FreeLocals(sequence);
}
private void DefineLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.OpenLocalScope();
foreach (var local in sequence.Locals)
{
DefineLocal(local, sequence.Syntax);
}
}
private void FreeLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.CloseLocalScope();
foreach (var local in sequence.Locals)
{
FreeLocal(local);
}
}
/// <summary>
/// Defines sequence locals and record them so that they could be retained for the duration of the encompassing expression
/// Use this when taking a reference of the sequence, which can indirectly refer to any of its locals.
/// </summary>
private void DefineAndRecordLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.OpenLocalScope();
foreach (var local in sequence.Locals)
{
var seqLocal = DefineLocal(local, sequence.Syntax);
AddExpressionTemp(seqLocal);
}
}
/// <summary>
/// Closes the visibility/debug scopes for the sequence locals, but keep the local slots from reuse
/// for the duration of the encompassing expression.
/// Use this paired with DefineAndRecordLocals when taking a reference of the sequence, which can indirectly refer to any of its locals.
/// </summary>
private void CloseScopeAndKeepLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.CloseLocalScope();
}
private void EmitSideEffects(BoundSequence sequence)
{
var sideEffects = sequence.SideEffects;
if (!sideEffects.IsDefaultOrEmpty)
{
foreach (var se in sideEffects)
{
EmitExpression(se, false);
}
}
}
private void EmitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt)
{
// We might have an extra argument for the __arglist() of a varargs method.
Debug.Assert(arguments.Length == parameters.Length || arguments.Length == parameters.Length + 1, "argument count must match parameter count");
Debug.Assert(parameters.All(p => p.RefKind == RefKind.None) || !argRefKindsOpt.IsDefault, "there are nontrivial parameters, so we must have argRefKinds");
Debug.Assert(argRefKindsOpt.IsDefault || argRefKindsOpt.Length == arguments.Length, "if we have argRefKinds, we should have one for each argument");
for (int i = 0; i < arguments.Length; i++)
{
RefKind argRefKind = GetArgumentRefKind(arguments, parameters, argRefKindsOpt, i);
EmitArgument(arguments[i], argRefKind);
}
}
/// <summary>
/// Computes the desired refkind of the argument.
/// Considers all the cases - where ref kinds are explicit, omitted, vararg cases.
/// </summary>
internal static RefKind GetArgumentRefKind(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt, int i)
{
RefKind argRefKind;
if (i < parameters.Length)
{
if (!argRefKindsOpt.IsDefault && i < argRefKindsOpt.Length)
{
// if we have an explicit refKind for the given argument, use that
argRefKind = argRefKindsOpt[i];
Debug.Assert(argRefKind == parameters[i].RefKind ||
argRefKind == RefKindExtensions.StrictIn && parameters[i].RefKind == RefKind.In,
"in Emit the argument RefKind must be compatible with the corresponding parameter");
}
else
{
// otherwise fallback to the refKind of the parameter
argRefKind = parameters[i].RefKind;
}
}
else
{
// vararg case
Debug.Assert(arguments[i].Kind == BoundKind.ArgListOperator);
argRefKind = RefKind.None;
}
return argRefKind;
}
private void EmitArrayElementLoad(BoundArrayAccess arrayAccess, bool used)
{
EmitExpression(arrayAccess.Expression, used: true);
EmitArrayIndices(arrayAccess.Indices);
if (((ArrayTypeSymbol)arrayAccess.Expression.Type).IsSZArray)
{
var elementType = arrayAccess.Type;
if (elementType.IsEnumType())
{
//underlying primitives do not need type tokens.
elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
}
switch (elementType.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Int8:
_builder.EmitOpCode(ILOpCode.Ldelem_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Ldelem_u1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int16:
_builder.EmitOpCode(ILOpCode.Ldelem_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Ldelem_u2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
_builder.EmitOpCode(ILOpCode.Ldelem_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Ldelem_u4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Ldelem_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Ldelem_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Ldelem_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Ldelem_r8);
break;
default:
if (elementType.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Ldelem_ref);
}
else
{
if (used)
{
_builder.EmitOpCode(ILOpCode.Ldelem);
}
else
{
// no need to read whole element of nontrivial type/size here
// just take a reference to an element for array access side-effects
if (elementType.TypeKind == TypeKind.TypeParameter)
{
_builder.EmitOpCode(ILOpCode.Readonly);
}
_builder.EmitOpCode(ILOpCode.Ldelema);
}
EmitSymbolToken(elementType, arrayAccess.Syntax);
}
break;
}
}
else
{
_builder.EmitArrayElementLoad(_module.Translate((ArrayTypeSymbol)arrayAccess.Expression.Type), arrayAccess.Expression.Syntax, _diagnostics);
}
EmitPopIfUnused(used);
}
private void EmitFieldLoad(BoundFieldAccess fieldAccess, bool used)
{
var field = fieldAccess.FieldSymbol;
if (!used)
{
// fetching unused captured frame is a no-op (like reading "this")
if (field.IsCapturedFrame)
{
return;
}
// Accessing a volatile field is sideeffecting because it establishes an acquire fence.
// Otherwise, accessing an unused instance field on a struct is a noop. Just emit an unused receiver.
if (!field.IsVolatile && !field.IsStatic && fieldAccess.ReceiverOpt.Type.IsVerifierValue())
{
EmitExpression(fieldAccess.ReceiverOpt, used: false);
return;
}
}
Debug.Assert(!field.IsConst || field.ContainingType.SpecialType == SpecialType.System_Decimal,
"rewriter should lower constant fields into constant expressions");
// static field access is sideeffecting since it guarantees that ..ctor has run.
// we emit static accesses even if unused.
if (field.IsStatic)
{
if (field.IsVolatile)
{
_builder.EmitOpCode(ILOpCode.Volatile);
}
_builder.EmitOpCode(ILOpCode.Ldsfld);
EmitSymbolToken(field, fieldAccess.Syntax);
}
else
{
var receiver = fieldAccess.ReceiverOpt;
TypeSymbol fieldType = field.Type;
if (fieldType.IsValueType && (object)fieldType == (object)receiver.Type)
{
//Handle emitting a field of a self-containing struct (only possible in mscorlib)
//since "val.field" is the same as val, we only need to emit val.
EmitExpression(receiver, used);
}
else
{
var temp = EmitFieldLoadReceiver(receiver);
if (temp != null)
{
Debug.Assert(FieldLoadMustUseRef(receiver), "only clr-ambiguous structs use temps here");
FreeTemp(temp);
}
if (field.IsVolatile)
{
_builder.EmitOpCode(ILOpCode.Volatile);
}
_builder.EmitOpCode(ILOpCode.Ldfld);
EmitSymbolToken(field, fieldAccess.Syntax);
}
}
EmitPopIfUnused(used);
}
private LocalDefinition EmitFieldLoadReceiver(BoundExpression receiver)
{
// ldfld can work with structs directly or with their addresses
// accessing via address is typically same or cheaper, but not for homeless values, obviously
// there are also cases where we must emit receiver as a reference
if (FieldLoadMustUseRef(receiver) || FieldLoadPrefersRef(receiver))
{
return EmitFieldLoadReceiverAddress(receiver) ? null : EmitReceiverRef(receiver, AddressKind.ReadOnly);
}
EmitExpression(receiver, true);
return null;
}
// In special case of loading the sequence of field accesses we can perform all the
// necessary field loads using the following IL:
//
// <expr>.a.b...y.z
// |
// V
// Unbox -or- Load.Ref (<expr>)
// Ldflda a
// Ldflda b
// ...
// Ldflda y
// Ldfld z
//
// Returns 'true' if the receiver was actually emitted this way
private bool EmitFieldLoadReceiverAddress(BoundExpression receiver)
{
if (receiver == null || !receiver.Type.IsValueType)
{
return false;
}
else if (receiver.Kind == BoundKind.Conversion)
{
var conversion = (BoundConversion)receiver;
if (conversion.ConversionKind == ConversionKind.Unboxing)
{
EmitExpression(conversion.Operand, true);
_builder.EmitOpCode(ILOpCode.Unbox);
EmitSymbolToken(receiver.Type, receiver.Syntax);
return true;
}
}
else if (receiver.Kind == BoundKind.FieldAccess)
{
var fieldAccess = (BoundFieldAccess)receiver;
var field = fieldAccess.FieldSymbol;
if (!field.IsStatic && EmitFieldLoadReceiverAddress(fieldAccess.ReceiverOpt))
{
Debug.Assert(!field.IsVolatile, "volatile valuetype fields are unexpected");
_builder.EmitOpCode(ILOpCode.Ldflda);
EmitSymbolToken(field, fieldAccess.Syntax);
return true;
}
}
return false;
}
// ldfld can work with structs directly or with their addresses
// In some cases it results in same native code emitted, but in some cases JIT pushes values for real
// resulting in much worse code (on x64 in particular).
// So, we will always prefer references here except when receiver is a struct non-ref local or parameter.
private bool FieldLoadPrefersRef(BoundExpression receiver)
{
// only fields of structs can be accessed via value
if (!receiver.Type.IsVerifierValue())
{
return true;
}
// can unbox directly into a ref.
if (receiver.Kind == BoundKind.Conversion && ((BoundConversion)receiver).ConversionKind == ConversionKind.Unboxing)
{
return true;
}
// can we take address at all?
if (!HasHome(receiver, AddressKind.ReadOnly))
{
return false;
}
switch (receiver.Kind)
{
case BoundKind.Parameter:
// prefer ldarg over ldarga
return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;
case BoundKind.Local:
// prefer ldloc over ldloca
return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;
case BoundKind.Sequence:
return FieldLoadPrefersRef(((BoundSequence)receiver).Value);
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)receiver;
if (fieldAccess.FieldSymbol.IsStatic)
{
return true;
}
if (DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
{
return false;
}
return FieldLoadPrefersRef(fieldAccess.ReceiverOpt);
}
return true;
}
internal static bool FieldLoadMustUseRef(BoundExpression expr)
{
var type = expr.Type;
// type parameter values must be boxed to get access to fields
if (type.IsTypeParameter())
{
return true;
}
// From Dev12/symbol.cpp
//
// // Used by ILGEN to determine if the type of this AggregateSymbol is one that the CLR
// // will consider ambiguous to an unmanaged pointer when it is on the stack (see VSW #396011)
// bool AggregateSymbol::IsCLRAmbigStruct()
// . . .
switch (type.SpecialType)
{
// case PT_BYTE:
case SpecialType.System_Byte:
// case PT_SHORT:
case SpecialType.System_Int16:
// case PT_INT:
case SpecialType.System_Int32:
// case PT_LONG:
case SpecialType.System_Int64:
// case PT_CHAR:
case SpecialType.System_Char:
// case PT_BOOL:
case SpecialType.System_Boolean:
// case PT_SBYTE:
case SpecialType.System_SByte:
// case PT_USHORT:
case SpecialType.System_UInt16:
// case PT_UINT:
case SpecialType.System_UInt32:
// case PT_ULONG:
case SpecialType.System_UInt64:
// case PT_INTPTR:
case SpecialType.System_IntPtr:
// case PT_UINTPTR:
case SpecialType.System_UIntPtr:
// case PT_FLOAT:
case SpecialType.System_Single:
// case PT_DOUBLE:
case SpecialType.System_Double:
// case PT_TYPEHANDLE:
case SpecialType.System_RuntimeTypeHandle:
// case PT_FIELDHANDLE:
case SpecialType.System_RuntimeFieldHandle:
// case PT_METHODHANDLE:
case SpecialType.System_RuntimeMethodHandle:
//case PT_ARGUMENTHANDLE:
case SpecialType.System_RuntimeArgumentHandle:
return true;
}
// this is for value__
// I do not know how to hit this, since value__ is not bindable in C#, but Dev12 has code to handle this
return type.IsEnumType();
}
private static int ParameterSlot(BoundParameter parameter)
{
var sym = parameter.ParameterSymbol;
int slot = sym.Ordinal;
if (!sym.ContainingSymbol.IsStatic)
{
slot++; // skip "this"
}
return slot;
}
private void EmitLocalLoad(BoundLocal local, bool used)
{
if (IsStackLocal(local.LocalSymbol))
{
// local must be already on the stack
EmitPopIfUnused(used);
}
else
{
if (used)
{
LocalDefinition definition = GetLocal(local);
_builder.EmitLocalLoad(definition);
}
else
{
// do nothing. Unused local load has no side-effects.
return;
}
}
if (used && local.LocalSymbol.RefKind != RefKind.None)
{
EmitLoadIndirect(local.LocalSymbol.Type, local.Syntax);
}
}
private void EmitParameterLoad(BoundParameter parameter)
{
int slot = ParameterSlot(parameter);
_builder.EmitLoadArgumentOpcode(slot);
if (parameter.ParameterSymbol.RefKind != RefKind.None)
{
var parameterType = parameter.ParameterSymbol.Type;
EmitLoadIndirect(parameterType, parameter.Syntax);
}
}
private void EmitLoadIndirect(TypeSymbol type, SyntaxNode syntaxNode)
{
if (type.IsEnumType())
{
//underlying primitives do not need type tokens.
type = ((NamedTypeSymbol)type).EnumUnderlyingType;
}
switch (type.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Int8:
_builder.EmitOpCode(ILOpCode.Ldind_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Ldind_u1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int16:
_builder.EmitOpCode(ILOpCode.Ldind_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Ldind_u2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
_builder.EmitOpCode(ILOpCode.Ldind_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Ldind_u4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Ldind_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Ldind_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Ldind_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Ldind_r8);
break;
default:
if (type.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Ldind_ref);
}
else
{
_builder.EmitOpCode(ILOpCode.Ldobj);
EmitSymbolToken(type, syntaxNode);
}
break;
}
}
/// <summary>
/// Used to decide if we need to emit call or callvirt.
/// It basically checks if the receiver expression cannot be null, but it is not 100% precise.
/// There are cases where it really can be null, but we do not care.
/// </summary>
private bool CanUseCallOnRefTypeReceiver(BoundExpression receiver)
{
// It seems none of the ways that could produce a receiver typed as a type param
// can guarantee that it is not null.
if (receiver.Type.IsTypeParameter())
{
return false;
}
Debug.Assert(receiver.Type.IsVerifierReference(), "this is not a reference");
Debug.Assert(receiver.Kind != BoundKind.BaseReference, "base should always use call");
var constVal = receiver.ConstantValue;
if (constVal != null)
{
// only when this is a constant Null, we need a callvirt
return !constVal.IsNull;
}
switch (receiver.Kind)
{
case BoundKind.ArrayCreation:
return true;
case BoundKind.ObjectCreationExpression:
// NOTE: there are cases involving ProxyAttribute
// where newobj may produce null
return true;
case BoundKind.Conversion:
var conversion = (BoundConversion)receiver;
switch (conversion.ConversionKind)
{
case ConversionKind.Boxing:
// NOTE: boxing can produce null for Nullable, but any call through that
// will result in null reference exceptions anyways.
return true;
case ConversionKind.MethodGroup:
case ConversionKind.AnonymousFunction:
return true;
case ConversionKind.ExplicitReference:
case ConversionKind.ImplicitReference:
return CanUseCallOnRefTypeReceiver(conversion.Operand);
}
break;
case BoundKind.ThisReference:
// NOTE: these actually can be null if called from a different language
// however, we assume it is responsibility of the caller to nullcheck "this"
// if we already have access to "this", we must be in a member and should
// not redo the check
return true;
case BoundKind.FieldAccess:
// same reason as for "ThisReference"
return ((BoundFieldAccess)receiver).FieldSymbol.IsCapturedFrame;
case BoundKind.Local:
// same reason as for "ThisReference"
return ((BoundLocal)receiver).LocalSymbol.SynthesizedKind == SynthesizedLocalKind.FrameCache;
case BoundKind.DelegateCreationExpression:
return true;
case BoundKind.Sequence:
var seqValue = ((BoundSequence)(receiver)).Value;
return CanUseCallOnRefTypeReceiver(seqValue);
case BoundKind.AssignmentOperator:
var rhs = ((BoundAssignmentOperator)receiver).Right;
return CanUseCallOnRefTypeReceiver(rhs);
case BoundKind.TypeOfOperator:
return true;
case BoundKind.ConditionalReceiver:
return true;
//TODO: there could be more cases where we can be sure that receiver is not a null.
}
return false;
}
/// <summary>
/// checks if receiver is effectively ldarg.0
/// </summary>
private bool IsThisReceiver(BoundExpression receiver)
{
switch (receiver.Kind)
{
case BoundKind.ThisReference:
return true;
case BoundKind.Sequence:
var seqValue = ((BoundSequence)(receiver)).Value;
return IsThisReceiver(seqValue);
}
return false;
}
private enum CallKind
{
Call,
CallVirt,
ConstrainedCallVirt,
}
private void EmitCallExpression(BoundCall call, UseKind useKind)
{
if (call.Method.IsDefaultValueTypeConstructor(requireZeroInit: true))
{
EmitDefaultValueTypeConstructorCallExpression(call);
}
else if (!call.Method.RequiresInstanceReceiver)
{
EmitStaticCallExpression(call, useKind);
}
else
{
EmitInstanceCallExpression(call, useKind);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EmitDefaultValueTypeConstructorCallExpression(BoundCall call)
{
var method = call.Method;
var receiver = call.ReceiverOpt;
// Calls to the default struct constructor are emitted as initobj, rather than call.
// NOTE: constructor invocations are represented as BoundObjectCreationExpressions,
// rather than BoundCalls. This is why we can be confident that if we see a call to a
// constructor, it has this very specific form.
Debug.Assert(method.IsImplicitlyDeclared);
Debug.Assert(TypeSymbol.Equals(method.ContainingType, receiver.Type, TypeCompareKind.ConsiderEverything2));
Debug.Assert(receiver.Kind == BoundKind.ThisReference);
LocalDefinition tempOpt = EmitReceiverRef(receiver, AddressKind.Writeable);
_builder.EmitOpCode(ILOpCode.Initobj); // initobj <MyStruct>
EmitSymbolToken(method.ContainingType, call.Syntax);
FreeOptTemp(tempOpt);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EmitStaticCallExpression(BoundCall call, UseKind useKind)
{
var method = call.Method;
var receiver = call.ReceiverOpt;
var arguments = call.Arguments;
Debug.Assert(method.IsStatic);
EmitArguments(arguments, method.Parameters, call.ArgumentRefKindsOpt);
int stackBehavior = GetCallStackBehavior(method, arguments);
if (method.IsAbstract)
{
if (receiver is not BoundTypeExpression { Type: { TypeKind: TypeKind.TypeParameter } })
{
throw ExceptionUtilities.Unreachable;
}
_builder.EmitOpCode(ILOpCode.Constrained);
EmitSymbolToken(receiver.Type, receiver.Syntax);
}
_builder.EmitOpCode(ILOpCode.Call, stackBehavior);
EmitSymbolToken(method, call.Syntax,
method.IsVararg ? (BoundArgListOperator)arguments[arguments.Length - 1] : null);
EmitCallCleanup(call.Syntax, useKind, method);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EmitInstanceCallExpression(BoundCall call, UseKind useKind)
{
var method = call.Method;
var receiver = call.ReceiverOpt;
var arguments = call.Arguments;
LocalDefinition tempOpt = null;
Debug.Assert(!method.IsStatic && method.RequiresInstanceReceiver);
CallKind callKind;
var receiverType = receiver.Type;
if (receiverType.IsVerifierReference())
{
EmitExpression(receiver, used: true);
// In some cases CanUseCallOnRefTypeReceiver returns true which means that
// null check is unnecessary and we can use "call"
if (receiver.SuppressVirtualCalls ||
(!method.IsMetadataVirtual() && CanUseCallOnRefTypeReceiver(receiver)))
{
callKind = CallKind.Call;
}
else
{
callKind = CallKind.CallVirt;
}
}
else if (receiverType.IsVerifierValue())
{
NamedTypeSymbol methodContainingType = method.ContainingType;
if (methodContainingType.IsVerifierValue())
{
// if method is defined in the struct itself it is assumed to be mutating, unless
// it is a member of a readonly struct and is not a constructor
var receiverAddresskind = IsReadOnlyCall(method, methodContainingType) ?
AddressKind.ReadOnly :
AddressKind.Writeable;
if (MayUseCallForStructMethod(method))
{
// NOTE: this should be either a method which overrides some abstract method or
// does not override anything (with few exceptions, see MayUseCallForStructMethod);
// otherwise we should not use direct 'call' and must use constrained call;
// calling a method defined in a value type
Debug.Assert(TypeSymbol.Equals(receiverType, methodContainingType, TypeCompareKind.ObliviousNullableModifierMatchesAny));
tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
callKind = CallKind.Call;
}
else
{
tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
callKind = CallKind.ConstrainedCallVirt;
}
}
else
{
// calling a method defined in a base class.
// When calling a method that is virtual in metadata on a struct receiver,
// we use a constrained virtual call. If possible, it will skip boxing.
if (method.IsMetadataVirtual())
{
// NB: all methods that a struct could inherit from bases are non-mutating
// treat receiver as ReadOnly
tempOpt = EmitReceiverRef(receiver, AddressKind.ReadOnly);
callKind = CallKind.ConstrainedCallVirt;
}
else
{
EmitExpression(receiver, used: true);
EmitBox(receiverType, receiver.Syntax);
callKind = CallKind.Call;
}
}
}
else
{
// receiver is generic and method must come from the base or an interface or a generic constraint
// if the receiver is actually a value type it would need to be boxed.
// let .constrained sort this out.
callKind = receiverType.IsReferenceType && !IsRef(receiver) ?
CallKind.CallVirt :
CallKind.ConstrainedCallVirt;
tempOpt = EmitReceiverRef(receiver, callKind == CallKind.ConstrainedCallVirt ? AddressKind.Constrained : AddressKind.Writeable);
}
// When emitting a callvirt to a virtual method we always emit the method info of the
// method that first declared the virtual method, not the method info of an
// overriding method. It would be a subtle breaking change to change that rule;
// see bug 6156 for details.
MethodSymbol actualMethodTargetedByTheCall = method;
if (method.IsOverride && callKind != CallKind.Call)
{
actualMethodTargetedByTheCall = method.GetConstructedLeastOverriddenMethod(_method.ContainingType, requireSameReturnType: true);
}
if (callKind == CallKind.ConstrainedCallVirt && actualMethodTargetedByTheCall.ContainingType.IsValueType)
{
// special case for overridden methods like ToString(...) called on
// value types: if the original method used in emit cannot use callvirt in this
// case, change it to Call.
callKind = CallKind.Call;
}
// Devirtualizing of calls to effectively sealed methods.
if (callKind == CallKind.CallVirt)
{
// NOTE: we check that we call method in same module just to be sure
// that it cannot be recompiled as not final and make our call not verifiable.
// such change by adversarial user would arguably be a compat break, but better be safe...
// In reality we would typically have one method calling another method in the same class (one GetEnumerator calling another).
// Other scenarios are uncommon since base class cannot be sealed and
// referring to a derived type in a different module is not an easy thing to do.
if (IsThisReceiver(receiver) && actualMethodTargetedByTheCall.ContainingType.IsSealed &&
(object)actualMethodTargetedByTheCall.ContainingModule == (object)_method.ContainingModule)
{
// special case for target is in a sealed class and "this" receiver.
Debug.Assert(receiver.Type.IsVerifierReference());
callKind = CallKind.Call;
}
// NOTE: we do not check that we call method in same module.
// Because of the "GetOriginalConstructedOverriddenMethod" above, the actual target
// can only be final when it is "newslot virtual final".
// In such case Dev11 emits "call" and we will just replicate the behavior. (see DevDiv: 546853 )
else if (actualMethodTargetedByTheCall.IsMetadataFinal && CanUseCallOnRefTypeReceiver(receiver))
{
// special case for calling 'final' virtual method on reference receiver
Debug.Assert(receiver.Type.IsVerifierReference());
callKind = CallKind.Call;
}
}
EmitArguments(arguments, method.Parameters, call.ArgumentRefKindsOpt);
int stackBehavior = GetCallStackBehavior(method, arguments);
switch (callKind)
{
case CallKind.Call:
_builder.EmitOpCode(ILOpCode.Call, stackBehavior);
break;
case CallKind.CallVirt:
_builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
break;
case CallKind.ConstrainedCallVirt:
_builder.EmitOpCode(ILOpCode.Constrained);
EmitSymbolToken(receiver.Type, receiver.Syntax);
_builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
break;
}
EmitSymbolToken(actualMethodTargetedByTheCall, call.Syntax,
actualMethodTargetedByTheCall.IsVararg ? (BoundArgListOperator)arguments[arguments.Length - 1] : null);
EmitCallCleanup(call.Syntax, useKind, method);
FreeOptTemp(tempOpt);
}
private bool IsReadOnlyCall(MethodSymbol method, NamedTypeSymbol methodContainingType)
{
Debug.Assert(methodContainingType.IsVerifierValue(), "only struct calls can be readonly");
if (method.IsEffectivelyReadOnly && method.MethodKind != MethodKind.Constructor)
{
return true;
}
if (methodContainingType.IsNullableType())
{
var originalMethod = method.OriginalDefinition;
if ((object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_GetValueOrDefault) ||
(object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value) ||
(object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue))
{
return true;
}
}
return false;
}
// returns true when receiver is already a ref.
// in such cases calling through a ref could be preferred over
// calling through indirectly loaded value.
private bool IsRef(BoundExpression receiver)
{
switch (receiver.Kind)
{
case BoundKind.Local:
return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;
case BoundKind.Parameter:
return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;
case BoundKind.Call:
return ((BoundCall)receiver).Method.RefKind != RefKind.None;
case BoundKind.FunctionPointerInvocation:
return ((BoundFunctionPointerInvocation)receiver).FunctionPointer.Signature.RefKind != RefKind.None;
case BoundKind.Dup:
return ((BoundDup)receiver).RefKind != RefKind.None;
case BoundKind.Sequence:
return IsRef(((BoundSequence)receiver).Value);
}
return false;
}
private static int GetCallStackBehavior(MethodSymbol method, ImmutableArray<BoundExpression> arguments)
{
int stack = 0;
if (!method.ReturnsVoid)
{
// The call puts the return value on the stack.
stack += 1;
}
if (method.RequiresInstanceReceiver)
{
// The call pops the receiver off the stack.
stack -= 1;
}
if (method.IsVararg)
{
// The call pops all the arguments, fixed and variadic.
int fixedArgCount = arguments.Length - 1;
int varArgCount = ((BoundArgListOperator)arguments[fixedArgCount]).Arguments.Length;
stack -= fixedArgCount;
stack -= varArgCount;
}
else
{
// The call pops all the arguments.
stack -= arguments.Length;
}
return stack;
}
private static int GetObjCreationStackBehavior(BoundObjectCreationExpression objCreation)
{
int stack = 0;
// Constructor puts the return value on the stack.
stack += 1;
if (objCreation.Constructor.IsVararg)
{
// Constructor pops all the arguments, fixed and variadic.
int fixedArgCount = objCreation.Arguments.Length - 1;
int varArgCount = ((BoundArgListOperator)objCreation.Arguments[fixedArgCount]).Arguments.Length;
stack -= fixedArgCount;
stack -= varArgCount;
}
else
{
// Constructor pops all the arguments.
stack -= objCreation.Arguments.Length;
}
return stack;
}
/// <summary>
/// Used to decide if we need to emit 'call' or 'callvirt' for structure method.
/// It basically checks if the method overrides any other and method's defining type
/// is not a 'special' or 'special-by-ref' type.
/// </summary>
internal static bool MayUseCallForStructMethod(MethodSymbol method)
{
Debug.Assert(method.ContainingType.IsVerifierValue(), "this is not a value type");
if (!method.IsMetadataVirtual() || method.IsStatic)
{
return true;
}
var overriddenMethod = method.OverriddenMethod;
if ((object)overriddenMethod == null || overriddenMethod.IsAbstract)
{
return true;
}
var containingType = method.ContainingType;
// overrides in structs that are special types can be called directly.
// we can assume that special types will not be removing overrides
return containingType.SpecialType != SpecialType.None;
}
/// <summary>
/// When array operation get long or ulong arguments the args should be
/// cast to native int.
/// Note that the cast is always checked.
/// </summary>
private void TreatLongsAsNative(Microsoft.Cci.PrimitiveTypeCode tc)
{
if (tc == Microsoft.Cci.PrimitiveTypeCode.Int64)
{
_builder.EmitOpCode(ILOpCode.Conv_ovf_i);
}
else if (tc == Microsoft.Cci.PrimitiveTypeCode.UInt64)
{
_builder.EmitOpCode(ILOpCode.Conv_ovf_i_un);
}
}
private void EmitArrayLength(BoundArrayLength expression, bool used)
{
// The binder recognizes Array.Length and Array.LongLength and creates BoundArrayLength for them.
//
// ArrayLength can be either
// int32 for Array.Length
// int64 for Array.LongLength
// UIntPtr for synthetic code that needs just check if length != 0 -
// this is used in "fixed(int* ptr = arr)"
Debug.Assert(expression.Type.SpecialType == SpecialType.System_Int32 ||
expression.Type.SpecialType == SpecialType.System_Int64 ||
expression.Type.SpecialType == SpecialType.System_UIntPtr);
// ldlen will null-check the expression so it must be "used"
EmitExpression(expression.Expression, used: true);
_builder.EmitOpCode(ILOpCode.Ldlen);
var typeTo = expression.Type.PrimitiveTypeCode;
// NOTE: ldlen returns native uint, but newarr takes native int, so the length value is always
// a positive native int. We can treat it as either signed or unsigned.
// We will use whatever typeTo says so we do not need to convert because of sign.
var typeFrom = typeTo.IsUnsigned() ? Microsoft.Cci.PrimitiveTypeCode.UIntPtr : Microsoft.Cci.PrimitiveTypeCode.IntPtr;
// NOTE: In Dev10 C# this cast is unchecked.
// That seems to be wrong since that would cause silent truncation on 64bit platform if that implements large arrays.
//
// Emitting checked conversion however results in redundant overflow checks on 64bit and also inhibits range check hoisting in loops.
// Therefore we will emit unchecked conversion here as C# compiler always did.
_builder.EmitNumericConversion(typeFrom, typeTo, @checked: false);
EmitPopIfUnused(used);
}
private void EmitArrayCreationExpression(BoundArrayCreation expression, bool used)
{
var arrayType = (ArrayTypeSymbol)expression.Type;
EmitArrayIndices(expression.Bounds);
if (arrayType.IsSZArray)
{
_builder.EmitOpCode(ILOpCode.Newarr);
EmitSymbolToken(arrayType.ElementType, expression.Syntax);
}
else
{
_builder.EmitArrayCreation(_module.Translate(arrayType), expression.Syntax, _diagnostics);
}
if (expression.InitializerOpt != null)
{
EmitArrayInitializers(arrayType, expression.InitializerOpt);
}
// newarr has side-effects (negative bounds etc) so always emitted.
EmitPopIfUnused(used);
}
private void EmitConvertedStackAllocExpression(BoundConvertedStackAllocExpression expression, bool used)
{
EmitExpression(expression.Count, used);
// the only sideeffect of a localloc is a nondeterministic and generally fatal StackOverflow.
// we can ignore that if the actual result is unused
if (used)
{
_sawStackalloc = true;
_builder.EmitOpCode(ILOpCode.Localloc);
}
var initializer = expression.InitializerOpt;
if (initializer != null)
{
if (used)
{
EmitStackAllocInitializers(expression.Type, initializer);
}
else
{
// If not used, just emit initializer elements to preserve possible sideeffects
foreach (var init in initializer.Initializers)
{
EmitExpression(init, used: false);
}
}
}
}
private void EmitObjectCreationExpression(BoundObjectCreationExpression expression, bool used)
{
MethodSymbol constructor = expression.Constructor;
if (constructor.IsDefaultValueTypeConstructor(requireZeroInit: true))
{
EmitInitObj(expression.Type, used, expression.Syntax);
}
else
{
// check if need to construct at all
if (!used && ConstructorNotSideEffecting(constructor))
{
// ctor has no side-effects, so we will just evaluate the arguments
foreach (var arg in expression.Arguments)
{
EmitExpression(arg, used: false);
}
return;
}
// ReadOnlySpan may just refer to the blob, if possible.
if (this._module.Compilation.IsReadOnlySpanType(expression.Type) &&
expression.Arguments.Length == 1)
{
if (TryEmitReadonlySpanAsBlobWrapper((NamedTypeSymbol)expression.Type, expression.Arguments[0], used, inPlace: false))
{
return;
}
}
// none of the above cases, so just create an instance
EmitArguments(expression.Arguments, constructor.Parameters, expression.ArgumentRefKindsOpt);
var stackAdjustment = GetObjCreationStackBehavior(expression);
_builder.EmitOpCode(ILOpCode.Newobj, stackAdjustment);
// for variadic ctors emit expanded ctor token
EmitSymbolToken(constructor, expression.Syntax,
constructor.IsVararg ? (BoundArgListOperator)expression.Arguments[expression.Arguments.Length - 1] : null);
EmitPopIfUnused(used);
}
}
/// <summary>
/// Recognizes constructors known to not have side-effects (which means they can be skipped unless the constructed object is used)
/// </summary>
private bool ConstructorNotSideEffecting(MethodSymbol constructor)
{
var originalDef = constructor.OriginalDefinition;
var compilation = _module.Compilation;
if (originalDef == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor))
{
return true;
}
if (originalDef.ContainingType.Name == NamedTypeSymbol.ValueTupleTypeName &&
(originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__ctor)))
{
return true;
}
return false;
}
private void EmitAssignmentExpression(BoundAssignmentOperator assignmentOperator, UseKind useKind)
{
if (TryEmitAssignmentInPlace(assignmentOperator, useKind != UseKind.Unused))
{
return;
}
// Assignment expression codegen has the following parts:
//
// * PreRHS: We need to emit instructions before the load of the right hand side if:
// - If the left hand side is a ref local or ref formal parameter and the right hand
// side is a value then we must put the ref on the stack early so that we can store
// indirectly into it.
// - If the left hand side is an array slot then we must evaluate the array and indices
// before we evaluate the right hand side. We ensure that the array and indices are
// on the stack when the store is executed.
// - Similarly, if the left hand side is a non-static field then its receiver must be
// evaluated before the right hand side.
//
// * RHS: There are three possible ways to do an assignment with respect to "refness",
// and all are found in the lowering of:
//
// N().s += 10;
//
// That expression is realized as
//
// ref int addr = ref N().s; // Assign a ref on the right hand side to the left hand side.
// int sum = addr + 10; // No refs at all; assign directly to sum.
// addr = sum; // Assigns indirectly through the address.
//
// - If we are in the first case then assignmentOperator.RefKind is Ref and the left hand side is a
// ref local temporary. We simply assign the ref on the RHS to the storage on the LHS with no indirection.
//
// - If we are in the second case then nothing is ref; we have a value on one side an a local on the other.
// Again, there is no indirection.
//
// - If we are in the third case then we have a ref on the left and a value on the right. We must compute the
// value of the right hand side and then store it into the left hand side.
//
// * Duplication: The result of an assignment operation is the value that was assigned. It is possible that
// later codegen is expecting this value to be on the stack when we're done here. This is controlled by
// the "used" formal parameter. There are two possible cases:
// - If the preamble put stuff on the stack for the usage of the store, then we must not put an extra copy
// of the right hand side value on the stack; that will be between the value and the stuff needed to
// do the storage. In that case we put the right hand side value in a temporary and restore it later.
// - Otherwise we can just do a dup instruction; there's nothing before the dup on the stack that we'll need.
//
// * Storage: Either direct or indirect, depending. See the RHS section above for details.
//
// * Post-storage: If we stashed away the duplicated value in the temporary, we need to restore it back to the stack.
bool lhsUsesStack = EmitAssignmentPreamble(assignmentOperator);
EmitAssignmentValue(assignmentOperator);
LocalDefinition temp = EmitAssignmentDuplication(assignmentOperator, useKind, lhsUsesStack);
EmitStore(assignmentOperator);
EmitAssignmentPostfix(assignmentOperator, temp, useKind);
}
// sometimes it is possible and advantageous to get an address of the lHS and
// perform assignment as an in-place initialization via initobj or constructor invocation.
//
// 1) initobj
// is used when assigning default value to T that is not a verifier reference.
//
// 2) in-place ctor call
// is used when assigning a freshly created struct. "x = new S(arg)" can be
// replaced by x.S(arg) as long as partial assignment cannot be observed -
// i.e. target must not be on the heap and we should not be in a try block.
private bool TryEmitAssignmentInPlace(BoundAssignmentOperator assignmentOperator, bool used)
{
// If the left hand is itself a ref, then we can't use in-place assignment
// because we need to spill the creation. This code can't be written in C#, but
// can be produced by lowering.
if (assignmentOperator.IsRef)
{
return false;
}
var left = assignmentOperator.Left;
// if result is used, and lives on heap, we must keep RHS value on the stack.
// otherwise we can try conjuring up the RHS value directly where it belongs.
if (used && !TargetIsNotOnHeap(left))
{
return false;
}
if (!SafeToGetWriteableReference(left))
{
// cannot take a ref
return false;
}
var right = assignmentOperator.Right;
var rightType = right.Type;
// in-place is not advantageous for reference types or constants
if (!rightType.IsTypeParameter())
{
if (rightType.IsReferenceType || (right.ConstantValue != null && rightType.SpecialType != SpecialType.System_Decimal))
{
return false;
}
}
if (right.IsDefaultValue())
{
InPlaceInit(left, used);
return true;
}
if (right is BoundObjectCreationExpression objCreation)
{
// If we are creating a Span<T> from a stackalloc, which is a particular pattern of code
// produced by lowering, we must use the constructor in its standard form because the stack
// is required to contain nothing more than stackalloc's argument.
if (objCreation.Arguments.Length > 0 && objCreation.Arguments[0].Kind == BoundKind.ConvertedStackAllocExpression)
{
return false;
}
// It is desirable to do in-place ctor call if possible.
// we could do newobj/stloc, but in-place call
// produces the same or better code in current JITs
if (PartialCtorResultCannotEscape(left))
{
var ctor = objCreation.Constructor;
// ctor can possibly see its own assignments indirectly if there are ref parameters or __arglist
if (System.Linq.ImmutableArrayExtensions.All(ctor.Parameters, p => p.RefKind == RefKind.None) &&
!ctor.IsVararg)
{
InPlaceCtorCall(left, objCreation, used);
return true;
}
}
}
return false;
}
private bool SafeToGetWriteableReference(BoundExpression left)
{
if (!HasHome(left, AddressKind.Writeable))
{
return false;
}
// because of array covariance, taking a reference to an element of
// generic array may fail even though assignment "arr[i] = default(T)" would always succeed.
if (left.Kind == BoundKind.ArrayAccess && left.Type.TypeKind == TypeKind.TypeParameter && !left.Type.IsValueType)
{
return false;
}
if (left.Kind == BoundKind.FieldAccess)
{
var fieldAccess = (BoundFieldAccess)left;
if (fieldAccess.FieldSymbol.IsVolatile ||
DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
{
return false;
}
}
return true;
}
private void InPlaceInit(BoundExpression target, bool used)
{
var temp = EmitAddress(target, AddressKind.Writeable);
Debug.Assert(temp == null, "in-place init target should not create temps");
_builder.EmitOpCode(ILOpCode.Initobj); // initobj <MyStruct>
EmitSymbolToken(target.Type, target.Syntax);
if (used)
{
Debug.Assert(TargetIsNotOnHeap(target), "cannot read-back the target since it could have been modified");
EmitExpression(target, used);
}
}
private void InPlaceCtorCall(BoundExpression target, BoundObjectCreationExpression objCreation, bool used)
{
Debug.Assert(TargetIsNotOnHeap(target), "in-place construction target should not be on heap");
var temp = EmitAddress(target, AddressKind.Writeable);
Debug.Assert(temp == null, "in-place ctor target should not create temps");
// ReadOnlySpan may just refer to the blob, if possible.
if (this._module.Compilation.IsReadOnlySpanType(objCreation.Type) && objCreation.Arguments.Length == 1)
{
if (TryEmitReadonlySpanAsBlobWrapper((NamedTypeSymbol)objCreation.Type, objCreation.Arguments[0], used, inPlace: true))
{
if (used)
{
EmitExpression(target, used: true);
}
return;
}
}
var constructor = objCreation.Constructor;
EmitArguments(objCreation.Arguments, constructor.Parameters, objCreation.ArgumentRefKindsOpt);
// -2 to adjust for consumed target address and not produced value.
var stackAdjustment = GetObjCreationStackBehavior(objCreation) - 2;
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment);
// for variadic ctors emit expanded ctor token
EmitSymbolToken(constructor, objCreation.Syntax,
constructor.IsVararg ? (BoundArgListOperator)objCreation.Arguments[objCreation.Arguments.Length - 1] : null);
if (used)
{
EmitExpression(target, used: true);
}
}
// partial ctor results are not observable when target is not on the heap.
// we also must not be in a try, otherwise if ctor throws
// partially assigned value may be observed in the handler.
private bool PartialCtorResultCannotEscape(BoundExpression left)
{
if (TargetIsNotOnHeap(left))
{
if (_tryNestingLevel != 0)
{
var local = left as BoundLocal;
if (local != null && !_builder.PossiblyDefinedOutsideOfTry(GetLocal(local)))
{
// local defined inside immediate Try - cannot escape
return true;
}
// local defined outside of immediate try or it is a parameter - can escape
return false;
}
// we are not in a try - locals, parameters cannot escape
return true;
}
// left is a reference, partial initializations can escape.
return false;
}
// returns True when assignment target is definitely not on the heap
private static bool TargetIsNotOnHeap(BoundExpression left)
{
switch (left.Kind)
{
case BoundKind.Parameter:
return ((BoundParameter)left).ParameterSymbol.RefKind == RefKind.None;
case BoundKind.Local:
// NOTE: stack locals are either homeless or refs, no need to special case them
// they will never be assigned in-place.
return ((BoundLocal)left).LocalSymbol.RefKind == RefKind.None;
}
return false;
}
private bool EmitAssignmentPreamble(BoundAssignmentOperator assignmentOperator)
{
var assignmentTarget = assignmentOperator.Left;
bool lhsUsesStack = false;
switch (assignmentTarget.Kind)
{
case BoundKind.RefValueOperator:
EmitRefValueAddress((BoundRefValueOperator)assignmentTarget);
break;
case BoundKind.FieldAccess:
{
var left = (BoundFieldAccess)assignmentTarget;
if (!left.FieldSymbol.IsStatic)
{
var temp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
Debug.Assert(temp == null, "temp is unexpected when assigning to a field");
lhsUsesStack = true;
}
}
break;
case BoundKind.Parameter:
{
var left = (BoundParameter)assignmentTarget;
if (left.ParameterSymbol.RefKind != RefKind.None &&
!assignmentOperator.IsRef)
{
_builder.EmitLoadArgumentOpcode(ParameterSlot(left));
lhsUsesStack = true;
}
}
break;
case BoundKind.Local:
{
var left = (BoundLocal)assignmentTarget;
// Again, consider our earlier case:
//
// ref int addr = ref N().s;
// int sum = addr + 10;
// addr = sum;
//
// There are three different ways we could be assigning to a local.
//
// In the first case, we want to simply call N(), take the address
// of s, and then store that address in addr.
//
// In the second case again we simply want to compute the sum and
// store the result in sum.
//
// In the third case however we want to first load the contents of
// addr -- the address of field s -- then put the sum on the stack,
// and then do an indirect store. In that case we need to have the
// contents of addr on the stack.
if (left.LocalSymbol.RefKind != RefKind.None && !assignmentOperator.IsRef)
{
if (!IsStackLocal(left.LocalSymbol))
{
LocalDefinition localDefinition = GetLocal(left);
_builder.EmitLocalLoad(localDefinition);
}
else
{
// this is a case of indirect assignment to a stack temp.
// currently byref temp can only be a stack local in scenarios where
// there is only one assignment and it is the last one.
// I do not yet know how to support cases where we assign more than once.
// That where Dup of LHS would be needed, but as a general scenario
// it is not always possible to handle. Fortunately all the cases where we
// indirectly assign to a byref temp come from rewriter and all
// they all are write-once cases.
//
// For now analyzer asserts that indirect writes are final reads of
// a ref local. And we never need a dup here.
// builder.EmitOpCode(ILOpCode.Dup);
}
lhsUsesStack = true;
}
}
break;
case BoundKind.ArrayAccess:
{
var left = (BoundArrayAccess)assignmentTarget;
EmitExpression(left.Expression, used: true);
EmitArrayIndices(left.Indices);
lhsUsesStack = true;
}
break;
case BoundKind.ThisReference:
{
var left = (BoundThisReference)assignmentTarget;
var temp = EmitAddress(left, AddressKind.Writeable);
Debug.Assert(temp == null, "taking ref of this should not create a temp");
lhsUsesStack = true;
}
break;
case BoundKind.Dup:
{
var left = (BoundDup)assignmentTarget;
var temp = EmitAddress(left, AddressKind.Writeable);
Debug.Assert(temp == null, "taking ref of Dup should not create a temp");
lhsUsesStack = true;
}
break;
case BoundKind.ConditionalOperator:
{
var left = (BoundConditionalOperator)assignmentTarget;
Debug.Assert(left.IsRef);
var temp = EmitAddress(left, AddressKind.Writeable);
Debug.Assert(temp == null, "taking ref of this should not create a temp");
lhsUsesStack = true;
}
break;
case BoundKind.PointerIndirectionOperator:
{
var left = (BoundPointerIndirectionOperator)assignmentTarget;
EmitExpression(left.Operand, used: true);
lhsUsesStack = true;
}
break;
case BoundKind.Sequence:
{
var sequence = (BoundSequence)assignmentTarget;
// NOTE: not releasing sequence locals right away.
// Since sequence is used as a variable, we will keep the locals for the extent of the containing expression
DefineAndRecordLocals(sequence);
EmitSideEffects(sequence);
lhsUsesStack = EmitAssignmentPreamble(assignmentOperator.Update(sequence.Value, assignmentOperator.Right, assignmentOperator.IsRef, assignmentOperator.Type));
CloseScopeAndKeepLocals(sequence);
}
break;
case BoundKind.Call:
{
var left = (BoundCall)assignmentTarget;
Debug.Assert(left.Method.RefKind != RefKind.None);
EmitCallExpression(left, UseKind.UsedAsAddress);
lhsUsesStack = true;
}
break;
case BoundKind.FunctionPointerInvocation:
{
var left = (BoundFunctionPointerInvocation)assignmentTarget;
Debug.Assert(left.FunctionPointer.Signature.RefKind != RefKind.None);
EmitCalli(left, UseKind.UsedAsAddress);
lhsUsesStack = true;
}
break;
case BoundKind.PropertyAccess:
case BoundKind.IndexerAccess:
// Property access should have been rewritten.
case BoundKind.PreviousSubmissionReference:
// Script references are lowered to a this reference and a field access.
throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);
case BoundKind.PseudoVariable:
EmitPseudoVariableAddress((BoundPseudoVariable)assignmentTarget);
lhsUsesStack = true;
break;
case BoundKind.ModuleVersionId:
case BoundKind.InstrumentationPayloadRoot:
break;
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)assignmentTarget;
if (!assignment.IsRef)
{
goto default;
}
EmitAssignmentExpression(assignment, UseKind.UsedAsAddress);
break;
default:
throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);
}
return lhsUsesStack;
}
private void EmitAssignmentValue(BoundAssignmentOperator assignmentOperator)
{
if (!assignmentOperator.IsRef)
{
EmitExpression(assignmentOperator.Right, used: true);
}
else
{
int exprTempsBefore = _expressionTemps?.Count ?? 0;
BoundExpression lhs = assignmentOperator.Left;
// NOTE: passing "ReadOnlyStrict" here.
// we should not get an address of a copy if at all possible
LocalDefinition temp = EmitAddress(assignmentOperator.Right, lhs.GetRefKind() == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
// Generally taking a ref for the purpose of ref assignment should not be done on homeless values
// however, there are very rare cases when we need to get a ref off a temp in synthetic code.
// Retain those temps for the extent of the encompassing expression.
AddExpressionTemp(temp);
var exprTempsAfter = _expressionTemps?.Count ?? 0;
// are we, by the way, ref-assigning to something that lives longer than encompassing expression?
Debug.Assert(lhs.Kind != BoundKind.Parameter || exprTempsAfter <= exprTempsBefore);
if (lhs.Kind == BoundKind.Local && ((BoundLocal)lhs).LocalSymbol.SynthesizedKind.IsLongLived())
{
// This situation is extremely rare. We are assigning a ref to a local with unknown lifetime
// while computing that ref required expression temps.
//
// We cannot reuse any of those temps and must leak them from the retained set.
// Any of them could be directly or indirectly referred by the LHS after the assignment.
// and we do not know the scope of the LHS - could be the whole method.
if (exprTempsAfter > exprTempsBefore)
{
_expressionTemps.Count = exprTempsBefore;
}
}
}
}
private LocalDefinition EmitAssignmentDuplication(BoundAssignmentOperator assignmentOperator, UseKind useKind, bool lhsUsesStack)
{
LocalDefinition temp = null;
if (useKind != UseKind.Unused)
{
_builder.EmitOpCode(ILOpCode.Dup);
if (lhsUsesStack)
{
// Today we sometimes have a case where we assign a ref directly to a temporary of ref type:
//
// ref int addr = ref N().y; <-- copies the address by value; no indirection
// int sum = addr + 10;
// addr = sum;
//
// If we have something like:
//
// ref int t1 = (ref int t2 = ref M().s);
//
// or the even more odd:
//
// int t1 = (ref int t2 = ref M().s);
//
// We need to figure out which of the situations above we are in, and ensure that the
// correct kind of temporary is created here. And also that either its value or its
// indirected value is read out after the store, in EmitAssignmentPostfix, below.
temp = AllocateTemp(
assignmentOperator.Left.Type,
assignmentOperator.Left.Syntax,
assignmentOperator.IsRef ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
_builder.EmitLocalStore(temp);
}
}
return temp;
}
private void EmitStore(BoundAssignmentOperator assignment)
{
BoundExpression expression = assignment.Left;
switch (expression.Kind)
{
case BoundKind.FieldAccess:
EmitFieldStore((BoundFieldAccess)expression);
break;
case BoundKind.Local:
// If we are doing a 'normal' local assignment like 'int t = 10;', or
// if we are initializing a temporary like 'ref int t = ref M().s;' then
// we just emit a local store. If we are doing an assignment through
// a ref local temporary then we assume that the instruction to load
// the address is already on the stack, and we must indirect through it.
// See the comments in EmitAssignmentExpression above for details.
BoundLocal local = (BoundLocal)expression;
if (local.LocalSymbol.RefKind != RefKind.None && !assignment.IsRef)
{
EmitIndirectStore(local.LocalSymbol.Type, local.Syntax);
}
else
{
if (IsStackLocal(local.LocalSymbol))
{
// assign to stack var == leave original value on stack
break;
}
else
{
_builder.EmitLocalStore(GetLocal(local));
}
}
break;
case BoundKind.ArrayAccess:
var array = ((BoundArrayAccess)expression).Expression;
var arrayType = (ArrayTypeSymbol)array.Type;
EmitArrayElementStore(arrayType, expression.Syntax);
break;
case BoundKind.ThisReference:
EmitThisStore((BoundThisReference)expression);
break;
case BoundKind.Parameter:
EmitParameterStore((BoundParameter)expression, assignment.IsRef);
break;
case BoundKind.Dup:
Debug.Assert(((BoundDup)expression).RefKind != RefKind.None);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.ConditionalOperator:
Debug.Assert(((BoundConditionalOperator)expression).IsRef);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.RefValueOperator:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PseudoVariable:
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.Sequence:
{
var sequence = (BoundSequence)expression;
EmitStore(assignment.Update(sequence.Value, assignment.Right, assignment.IsRef, assignment.Type));
}
break;
case BoundKind.Call:
Debug.Assert(((BoundCall)expression).Method.RefKind != RefKind.None);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.FunctionPointerInvocation:
Debug.Assert(((BoundFunctionPointerInvocation)expression).FunctionPointer.Signature.RefKind != RefKind.None);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.ModuleVersionId:
EmitModuleVersionIdStore((BoundModuleVersionId)expression);
break;
case BoundKind.InstrumentationPayloadRoot:
EmitInstrumentationPayloadRootStore((BoundInstrumentationPayloadRoot)expression);
break;
case BoundKind.AssignmentOperator:
var nested = (BoundAssignmentOperator)expression;
if (!nested.IsRef)
{
goto default;
}
EmitIndirectStore(nested.Type, expression.Syntax);
break;
case BoundKind.PreviousSubmissionReference:
// Script references are lowered to a this reference and a field access.
default:
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
}
}
private void EmitAssignmentPostfix(BoundAssignmentOperator assignment, LocalDefinition temp, UseKind useKind)
{
if (temp != null)
{
if (useKind == UseKind.UsedAsAddress)
{
_builder.EmitLocalAddress(temp);
}
else
{
_builder.EmitLocalLoad(temp);
}
FreeTemp(temp);
}
if (useKind == UseKind.UsedAsValue && assignment.IsRef)
{
EmitLoadIndirect(assignment.Type, assignment.Syntax);
}
}
private void EmitThisStore(BoundThisReference thisRef)
{
Debug.Assert(thisRef.Type.IsValueType);
_builder.EmitOpCode(ILOpCode.Stobj);
EmitSymbolToken(thisRef.Type, thisRef.Syntax);
}
private void EmitArrayElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
{
if (arrayType.IsSZArray)
{
EmitVectorElementStore(arrayType, syntaxNode);
}
else
{
_builder.EmitArrayElementStore(_module.Translate(arrayType), syntaxNode, _diagnostics);
}
}
/// <summary>
/// Emit an element store instruction for a single dimensional array.
/// </summary>
private void EmitVectorElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
{
var elementType = arrayType.ElementType;
if (elementType.IsEnumType())
{
//underlying primitives do not need type tokens.
elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
}
switch (elementType.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.Int8:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Stelem_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.Int16:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Stelem_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Stelem_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Stelem_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Stelem_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Stelem_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Stelem_r8);
break;
default:
if (elementType.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Stelem_ref);
}
else
{
_builder.EmitOpCode(ILOpCode.Stelem);
EmitSymbolToken(elementType, syntaxNode);
}
break;
}
}
private void EmitFieldStore(BoundFieldAccess fieldAccess)
{
var field = fieldAccess.FieldSymbol;
if (field.IsVolatile)
{
_builder.EmitOpCode(ILOpCode.Volatile);
}
_builder.EmitOpCode(field.IsStatic ? ILOpCode.Stsfld : ILOpCode.Stfld);
EmitSymbolToken(field, fieldAccess.Syntax);
}
private void EmitParameterStore(BoundParameter parameter, bool refAssign)
{
int slot = ParameterSlot(parameter);
if (parameter.ParameterSymbol.RefKind != RefKind.None && !refAssign)
{
//NOTE: we should have the actual parameter already loaded,
//now need to do a store to where it points to
EmitIndirectStore(parameter.ParameterSymbol.Type, parameter.Syntax);
}
else
{
_builder.EmitStoreArgumentOpcode(slot);
}
}
private void EmitIndirectStore(TypeSymbol type, SyntaxNode syntaxNode)
{
if (type.IsEnumType())
{
//underlying primitives do not need type tokens.
type = ((NamedTypeSymbol)type).EnumUnderlyingType;
}
switch (type.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.Int8:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Stind_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.Int16:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Stind_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Stind_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Stind_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Stind_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Stind_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Stind_r8);
break;
default:
if (type.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Stind_ref);
}
else
{
_builder.EmitOpCode(ILOpCode.Stobj);
EmitSymbolToken(type, syntaxNode);
}
break;
}
}
private void EmitPopIfUnused(bool used)
{
if (!used)
{
_builder.EmitOpCode(ILOpCode.Pop);
}
}
private void EmitIsExpression(BoundIsOperator isOp, bool used)
{
var operand = isOp.Operand;
EmitExpression(operand, used);
if (used)
{
Debug.Assert((object)operand.Type != null);
if (!operand.Type.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operand.Type, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(isOp.TargetType.Type, isOp.Syntax);
_builder.EmitOpCode(ILOpCode.Ldnull);
_builder.EmitOpCode(ILOpCode.Cgt_un);
}
}
private void EmitAsExpression(BoundAsOperator asOp, bool used)
{
Debug.Assert(!asOp.Conversion.Kind.IsImplicitConversion());
var operand = asOp.Operand;
EmitExpression(operand, used);
if (used)
{
var operandType = operand.Type;
var targetType = asOp.Type;
Debug.Assert((object)targetType != null);
if ((object)operandType != null && !operandType.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operandType, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(targetType, asOp.Syntax);
if (!targetType.IsVerifierReference())
{
// We need to unbox if the target type is not a reference type
_builder.EmitOpCode(ILOpCode.Unbox_any);
EmitSymbolToken(targetType, asOp.Syntax);
}
}
}
private void EmitDefaultValue(TypeSymbol type, bool used, SyntaxNode syntaxNode)
{
if (used)
{
// default type parameter values must be emitted as 'initobj' regardless of constraints
if (!type.IsTypeParameter() && type.SpecialType != SpecialType.System_Decimal)
{
var constantValue = type.GetDefaultValue();
if (constantValue != null)
{
_builder.EmitConstantValue(constantValue);
return;
}
}
if (type.IsPointerOrFunctionPointer() || type.SpecialType == SpecialType.System_UIntPtr)
{
// default(whatever*) and default(UIntPtr) can be emitted as:
_builder.EmitOpCode(ILOpCode.Ldc_i4_0);
_builder.EmitOpCode(ILOpCode.Conv_u);
}
else if (type.SpecialType == SpecialType.System_IntPtr)
{
_builder.EmitOpCode(ILOpCode.Ldc_i4_0);
_builder.EmitOpCode(ILOpCode.Conv_i);
}
else
{
EmitInitObj(type, true, syntaxNode);
}
}
}
private void EmitDefaultExpression(BoundDefaultExpression expression, bool used)
{
Debug.Assert(expression.Type.SpecialType == SpecialType.System_Decimal ||
expression.Type.GetDefaultValue() == null, "constant should be set on this expression");
// Default value for the given default expression is not a constant
// Expression must be of type parameter type or a non-primitive value type
// Emit an initobj instruction for these cases
EmitDefaultValue(expression.Type, used, expression.Syntax);
}
private void EmitConstantExpression(TypeSymbol type, ConstantValue constantValue, bool used, SyntaxNode syntaxNode)
{
if (used) // unused constant has no side-effects
{
// Null type parameter values must be emitted as 'initobj' rather than 'ldnull'.
if (((object)type != null) && (type.TypeKind == TypeKind.TypeParameter) && constantValue.IsNull)
{
EmitInitObj(type, used, syntaxNode);
}
else
{
_builder.EmitConstantValue(constantValue);
}
}
}
private void EmitInitObj(TypeSymbol type, bool used, SyntaxNode syntaxNode)
{
if (used)
{
var temp = this.AllocateTemp(type, syntaxNode);
_builder.EmitLocalAddress(temp); // ldloca temp
_builder.EmitOpCode(ILOpCode.Initobj); // initobj <MyStruct>
EmitSymbolToken(type, syntaxNode);
_builder.EmitLocalLoad(temp); // ldloc temp
FreeTemp(temp);
}
}
private void EmitGetTypeFromHandle(BoundTypeOf boundTypeOf)
{
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
var getTypeMethod = boundTypeOf.GetTypeFromHandle;
Debug.Assert((object)getTypeMethod != null); // Should have been checked during binding
EmitSymbolToken(getTypeMethod, boundTypeOf.Syntax, null);
}
private void EmitTypeOfExpression(BoundTypeOfOperator boundTypeOfOperator)
{
TypeSymbol type = boundTypeOfOperator.SourceType.Type;
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(type, boundTypeOfOperator.SourceType.Syntax);
EmitGetTypeFromHandle(boundTypeOfOperator);
}
private void EmitSizeOfExpression(BoundSizeOfOperator boundSizeOfOperator)
{
TypeSymbol type = boundSizeOfOperator.SourceType.Type;
_builder.EmitOpCode(ILOpCode.Sizeof);
EmitSymbolToken(type, boundSizeOfOperator.SourceType.Syntax);
}
private void EmitMethodDefIndexExpression(BoundMethodDefIndex node)
{
Debug.Assert(node.Method.IsDefinition);
Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
_builder.EmitOpCode(ILOpCode.Ldtoken);
// For partial methods, we emit pseudo token based on the symbol for the partial
// definition part as opposed to the symbol for the partial implementation part.
// We will need to resolve the symbol associated with each pseudo token in order
// to compute the real method definition tokens later. For partial methods, this
// resolution can only succeed if the associated symbol is the symbol for the
// partial definition and not the symbol for the partial implementation (see
// MethodSymbol.ResolvedMethodImpl()).
var symbol = node.Method.PartialDefinitionPart ?? node.Method;
EmitSymbolToken(symbol, node.Syntax, null, encodeAsRawDefinitionToken: true);
}
private void EmitMaximumMethodDefIndexExpression(BoundMaximumMethodDefIndex node)
{
Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
_builder.EmitOpCode(ILOpCode.Ldtoken);
_builder.EmitGreatestMethodToken();
}
private void EmitModuleVersionIdLoad(BoundModuleVersionId node)
{
_builder.EmitOpCode(ILOpCode.Ldsfld);
EmitModuleVersionIdToken(node);
}
private void EmitModuleVersionIdStore(BoundModuleVersionId node)
{
_builder.EmitOpCode(ILOpCode.Stsfld);
EmitModuleVersionIdToken(node);
}
private void EmitModuleVersionIdToken(BoundModuleVersionId node)
{
_builder.EmitToken(_module.GetModuleVersionId(_module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
}
private void EmitModuleVersionIdStringLoad(BoundModuleVersionIdString node)
{
_builder.EmitOpCode(ILOpCode.Ldstr);
_builder.EmitModuleVersionIdStringToken();
}
private void EmitInstrumentationPayloadRootLoad(BoundInstrumentationPayloadRoot node)
{
_builder.EmitOpCode(ILOpCode.Ldsfld);
EmitInstrumentationPayloadRootToken(node);
}
private void EmitInstrumentationPayloadRootStore(BoundInstrumentationPayloadRoot node)
{
_builder.EmitOpCode(ILOpCode.Stsfld);
EmitInstrumentationPayloadRootToken(node);
}
private void EmitInstrumentationPayloadRootToken(BoundInstrumentationPayloadRoot node)
{
_builder.EmitToken(_module.GetInstrumentationPayloadRoot(node.AnalysisKind, _module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
}
private void EmitSourceDocumentIndex(BoundSourceDocumentIndex node)
{
Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
_builder.EmitOpCode(ILOpCode.Ldtoken);
_builder.EmitSourceDocumentIndexToken(node.Document);
}
private void EmitMethodInfoExpression(BoundMethodInfo node)
{
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Method, node.Syntax, null);
MethodSymbol getMethod = node.GetMethodFromHandle;
Debug.Assert((object)getMethod != null);
if (getMethod.ParameterCount == 1)
{
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
}
else
{
Debug.Assert(getMethod.ParameterCount == 2);
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Method.ContainingType, node.Syntax);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
}
EmitSymbolToken(getMethod, node.Syntax, null);
if (!TypeSymbol.Equals(node.Type, getMethod.ReturnType, TypeCompareKind.ConsiderEverything2))
{
_builder.EmitOpCode(ILOpCode.Castclass);
EmitSymbolToken(node.Type, node.Syntax);
}
}
private void EmitFieldInfoExpression(BoundFieldInfo node)
{
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Field, node.Syntax);
MethodSymbol getField = node.GetFieldFromHandle;
Debug.Assert((object)getField != null);
if (getField.ParameterCount == 1)
{
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
}
else
{
Debug.Assert(getField.ParameterCount == 2);
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Field.ContainingType, node.Syntax);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
}
EmitSymbolToken(getField, node.Syntax, null);
if (!TypeSymbol.Equals(node.Type, getField.ReturnType, TypeCompareKind.ConsiderEverything2))
{
_builder.EmitOpCode(ILOpCode.Castclass);
EmitSymbolToken(node.Type, node.Syntax);
}
}
/// <summary>
/// Emit code for a conditional (aka ternary) operator.
/// </summary>
/// <remarks>
/// (b ? x : y) becomes
/// push b
/// if pop then goto CONSEQUENCE
/// push y
/// goto DONE
/// CONSEQUENCE:
/// push x
/// DONE:
/// </remarks>
private void EmitConditionalOperator(BoundConditionalOperator expr, bool used)
{
Debug.Assert(expr.ConstantValue == null, "Constant value should have been emitted directly");
object consequenceLabel = new object();
object doneLabel = new object();
EmitCondBranch(expr.Condition, ref consequenceLabel, sense: true);
EmitExpression(expr.Alternative, used);
//
// III.1.8.1.3 Merging stack states
// . . .
// Let T be the type from the slot on the newly computed state and S
// be the type from the corresponding slot on the previously stored state. The merged type, U, shall
// be computed as follows (recall that S := T is the compatibility function defined
// in §III.1.8.1.2.2):
// 1. if S := T then U=S
// 2. Otherwise, if T := S then U=T
// 3. Otherwise, if S and T are both object types, then let V be the closest common supertype of S and T then U=V.
// 4. Otherwise, the merge shall fail.
//
// When the target merge type is an interface that one or more classes implement, we emit static casts
// from any class to the target interface.
// You may think that it's possible to elide one of the static casts and have the CLR recognize
// that merging a class and interface should succeed if the class implements the interface. Unfortunately,
// it seems that either PEVerify or the runtime/JIT verifier will complain at you if you try to remove
// either of the casts.
//
var mergeTypeOfAlternative = StackMergeType(expr.Alternative);
if (used)
{
if (IsVarianceCast(expr.Type, mergeTypeOfAlternative))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfAlternative = expr.Type;
}
else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfAlternative, TypeCompareKind.ConsiderEverything2))
{
EmitStaticCast(expr.Type, expr.Syntax);
}
}
_builder.EmitBranch(ILOpCode.Br, doneLabel);
if (used)
{
// If we get to consequenceLabel, we should not have Alternative on stack, adjust for that.
_builder.AdjustStack(-1);
}
_builder.MarkLabel(consequenceLabel);
EmitExpression(expr.Consequence, used);
if (used)
{
var mergeTypeOfConsequence = StackMergeType(expr.Consequence);
if (IsVarianceCast(expr.Type, mergeTypeOfConsequence))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfConsequence = expr.Type;
}
else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfConsequence, TypeCompareKind.ConsiderEverything2))
{
EmitStaticCast(expr.Type, expr.Syntax);
}
}
_builder.MarkLabel(doneLabel);
}
/// <summary>
/// Emit code for a null-coalescing operator.
/// </summary>
/// <remarks>
/// x ?? y becomes
/// push x
/// dup x
/// if pop != null goto LEFT_NOT_NULL
/// pop
/// push y
/// LEFT_NOT_NULL:
/// </remarks>
private void EmitNullCoalescingOperator(BoundNullCoalescingOperator expr, bool used)
{
Debug.Assert(expr.LeftConversion.IsIdentity, "coalesce with nontrivial left conversions are lowered into conditional.");
Debug.Assert(expr.Type.IsReferenceType);
EmitExpression(expr.LeftOperand, used: true);
// See the notes about verification type merges in EmitConditionalOperator
var mergeTypeOfLeftValue = StackMergeType(expr.LeftOperand);
if (used)
{
if (IsVarianceCast(expr.Type, mergeTypeOfLeftValue))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfLeftValue = expr.Type;
}
else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfLeftValue, TypeCompareKind.ConsiderEverything2))
{
EmitStaticCast(expr.Type, expr.Syntax);
}
_builder.EmitOpCode(ILOpCode.Dup);
}
if (expr.Type.IsTypeParameter())
{
EmitBox(expr.Type, expr.LeftOperand.Syntax);
}
object ifLeftNotNullLabel = new object();
_builder.EmitBranch(ILOpCode.Brtrue, ifLeftNotNullLabel);
if (used)
{
_builder.EmitOpCode(ILOpCode.Pop);
}
EmitExpression(expr.RightOperand, used);
if (used)
{
var mergeTypeOfRightValue = StackMergeType(expr.RightOperand);
if (IsVarianceCast(expr.Type, mergeTypeOfRightValue))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfRightValue = expr.Type;
}
}
_builder.MarkLabel(ifLeftNotNullLabel);
}
// Implicit casts are not emitted. As a result verifier may operate on a different
// types from the types of operands when performing stack merges in coalesce/conditional.
// Such differences are in general irrelevant since merging rules work the same way
// for base and derived types.
//
// Situation becomes more complicated with delegates, arrays and interfaces since they
// allow implicit casts from types that do not derive from them. In such cases
// we may need to introduce static casts in the code to prod the verifier to the
// right direction
//
// This helper returns actual type of array|interface|delegate expression ignoring implicit
// casts. This would be the effective stack merge type in the verifier.
//
// NOTE: In cases where stack merge type cannot be determined, we just return null.
// We still must assume that it can be an array, delegate or interface though.
private TypeSymbol StackMergeType(BoundExpression expr)
{
// these cases are not interesting. Merge type is the same or derived. No difference.
if (!(expr.Type.IsInterfaceType() || expr.Type.IsDelegateType()))
{
return expr.Type;
}
// Dig through casts. We only need to check for expressions that -
// 1) implicit casts
// 2) transparently return operands, so we need to dig deeper
// 3) stack values
switch (expr.Kind)
{
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
var conversionKind = conversion.ConversionKind;
Debug.Assert(conversionKind != ConversionKind.NullLiteral && conversionKind != ConversionKind.DefaultLiteral);
if (conversionKind.IsImplicitConversion() &&
conversionKind != ConversionKind.MethodGroup &&
conversionKind != ConversionKind.NullLiteral &&
conversionKind != ConversionKind.DefaultLiteral)
{
return StackMergeType(conversion.Operand);
}
break;
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
return StackMergeType(assignment.Right);
case BoundKind.Sequence:
var sequence = (BoundSequence)expr;
return StackMergeType(sequence.Value);
case BoundKind.Local:
var local = (BoundLocal)expr;
if (this.IsStackLocal(local.LocalSymbol))
{
// stack value, we cannot be sure what it is
return null;
}
break;
case BoundKind.Dup:
// stack value, we cannot be sure what it is
return null;
}
return expr.Type;
}
// Although III.1.8.1.3 seems to imply that verifier understands variance casts.
// It appears that verifier/JIT gets easily confused.
// So to not rely on whether that should work or not we will flag potentially
// "complicated" casts and make them static casts to ensure we are all on
// the same page with what type should be tracked.
private static bool IsVarianceCast(TypeSymbol to, TypeSymbol from)
{
if (TypeSymbol.Equals(to, from, TypeCompareKind.ConsiderEverything2))
{
return false;
}
if ((object)from == null)
{
// from unknown type - this could be a variance conversion.
return true;
}
// while technically variance casts, array conversions do not seem to be a problem
// unless the element types are converted via variance.
if (to.IsArray())
{
return IsVarianceCast(((ArrayTypeSymbol)to).ElementType, ((ArrayTypeSymbol)from).ElementType);
}
return (to.IsDelegateType() && !TypeSymbol.Equals(to, from, TypeCompareKind.ConsiderEverything2)) ||
(to.IsInterfaceType() && from.IsInterfaceType() && !from.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey((NamedTypeSymbol)to));
}
private void EmitStaticCast(TypeSymbol to, SyntaxNode syntax)
{
Debug.Assert(to.IsVerifierReference());
// From ILGENREC::GenQMark
// See VSWhidbey Bugs #49619 and 108643. If the destination type is an interface we need
// to force a static cast to be generated for any cast result expressions. The static cast
// should be done before the unifying jump so the code is verifiable and to allow the JIT to
// optimize it away. NOTE: Since there is no staticcast instruction, we implement static cast
// with a stloc / ldloc to a temporary.
// Bug: VSWhidbey/49619
// Bug: VSWhidbey/108643
// Bug: Devdiv/42645
var temp = AllocateTemp(to, syntax);
_builder.EmitLocalStore(temp);
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
}
private void EmitBox(TypeSymbol type, SyntaxNode syntaxNode)
{
Debug.Assert(!type.IsRefLikeType);
_builder.EmitOpCode(ILOpCode.Box);
EmitSymbolToken(type, syntaxNode);
}
private void EmitCalli(BoundFunctionPointerInvocation ptrInvocation, UseKind useKind)
{
EmitExpression(ptrInvocation.InvokedExpression, used: true);
LocalDefinition temp = null;
// The function pointer token must be the last thing on the stack before the
// calli invocation, but we need to preserve left-to-right semantics of the
// actual code. If there are arguments, therefore, we evaluate the code that
// produces the function pointer token, store it in a local, evaluate the
// arguments, then load that token again.
if (ptrInvocation.Arguments.Length > 0)
{
temp = AllocateTemp(ptrInvocation.InvokedExpression.Type, ptrInvocation.Syntax);
_builder.EmitLocalStore(temp);
}
FunctionPointerMethodSymbol method = ptrInvocation.FunctionPointer.Signature;
EmitArguments(ptrInvocation.Arguments, method.Parameters, ptrInvocation.ArgumentRefKindsOpt);
var stackBehavior = GetCallStackBehavior(ptrInvocation.FunctionPointer.Signature, ptrInvocation.Arguments);
if (temp is object)
{
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
}
_builder.EmitOpCode(ILOpCode.Calli, stackBehavior);
EmitSignatureToken(ptrInvocation.FunctionPointer, ptrInvocation.Syntax);
EmitCallCleanup(ptrInvocation.Syntax, useKind, method);
}
private void EmitCallCleanup(SyntaxNode syntax, UseKind useKind, MethodSymbol method)
{
if (!method.ReturnsVoid)
{
EmitPopIfUnused(useKind != UseKind.Unused);
}
else if (_ilEmitStyle == ILEmitStyle.Debug)
{
// The only void methods with usable return values are constructors and the only
// time we see them here, the return should be unused.
Debug.Assert(useKind == UseKind.Unused, "Using the return value of a void method.");
Debug.Assert(_method.GenerateDebugInfo, "Implied by this.emitSequencePoints");
// DevDiv #15135. When a method like System.Diagnostics.Debugger.Break() is called, the
// debugger sees an event indicating that a user break (vs a breakpoint) has occurred.
// When this happens, it uses ICorDebugILFrame.GetIP(out uint, out CorDebugMappingResult)
// to determine the current instruction pointer. This method returns the instruction
// *after* the call. The source location is then given by the last sequence point before
// or on this instruction. As a result, if the instruction after the call has its own
// sequence point, then that sequence point will be used to determine the source location
// and the debugging experience will be disrupted. The easiest way to ensure that the next
// instruction does not have a sequence point is to insert a nop. Obviously, we only do this
// if debugging is enabled and optimization is disabled.
// From ILGENREC::genCall:
// We want to generate a NOP after CALL opcodes that end a statement so the debugger
// has better stepping behavior
// CONSIDER: In the native compiler, there's an additional restriction on when this nop is
// inserted. It is quite complicated, but it basically seems to say that, if we thought
// we could omit the temp-and-copy for a struct construction and it turned out that we
// couldn't (perhaps because the assigned local was captured by a lambda), and if we're
// not using the result of the constructor call (how can this even happen?), then we don't
// want to insert the nop. Since the consequence of not implementing this complicated logic
// is an extra nop in debug code, this is likely not a priority.
// CONSIDER: The native compiler also checks !(tree->flags & EXF_NODEBUGINFO). We don't have
// this mutable bit on our bound nodes, so we can't exactly match the behavior. We might be
// able to approximate the native behavior by inspecting call.WasCompilerGenerated, but it is
// not in a reliable state after lowering.
_builder.EmitOpCode(ILOpCode.Nop);
}
if (useKind == UseKind.UsedAsValue && method.RefKind != RefKind.None)
{
EmitLoadIndirect(method.ReturnType, syntax);
}
else if (useKind == UseKind.UsedAsAddress)
{
Debug.Assert(method.RefKind != RefKind.None);
}
}
private void EmitLoadFunction(BoundFunctionPointerLoad load, bool used)
{
Debug.Assert(load.Type is { TypeKind: TypeKind.FunctionPointer });
if (used)
{
if (load.TargetMethod.IsAbstract && load.TargetMethod.IsStatic)
{
if (load.ConstrainedToTypeOpt is not { TypeKind: TypeKind.TypeParameter })
{
throw ExceptionUtilities.Unreachable;
}
_builder.EmitOpCode(ILOpCode.Constrained);
EmitSymbolToken(load.ConstrainedToTypeOpt, load.Syntax);
}
_builder.EmitOpCode(ILOpCode.Ldftn);
EmitSymbolToken(load.TargetMethod, load.Syntax, optArgList: null);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
using static System.Linq.ImmutableArrayExtensions;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal partial class CodeGenerator
{
private int _recursionDepth;
private class EmitCancelledException : Exception
{ }
private enum UseKind
{
Unused,
UsedAsValue,
UsedAsAddress
}
private void EmitExpression(BoundExpression expression, bool used)
{
if (expression == null)
{
return;
}
var constantValue = expression.ConstantValue;
if (constantValue != null)
{
if (!used)
{
// unused constants have no side-effects.
return;
}
if ((object)expression.Type == null || expression.Type.SpecialType != SpecialType.System_Decimal)
{
EmitConstantExpression(expression.Type, constantValue, used, expression.Syntax);
return;
}
}
_recursionDepth++;
if (_recursionDepth > 1)
{
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
EmitExpressionCore(expression, used);
}
else
{
EmitExpressionCoreWithStackGuard(expression, used);
}
_recursionDepth--;
}
private void EmitExpressionCoreWithStackGuard(BoundExpression expression, bool used)
{
Debug.Assert(_recursionDepth == 1);
try
{
EmitExpressionCore(expression, used);
Debug.Assert(_recursionDepth == 1);
}
catch (InsufficientExecutionStackException)
{
_diagnostics.Add(ErrorCode.ERR_InsufficientStack,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(expression));
throw new EmitCancelledException();
}
}
private void EmitExpressionCore(BoundExpression expression, bool used)
{
switch (expression.Kind)
{
case BoundKind.AssignmentOperator:
EmitAssignmentExpression((BoundAssignmentOperator)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.Call:
EmitCallExpression((BoundCall)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.ObjectCreationExpression:
EmitObjectCreationExpression((BoundObjectCreationExpression)expression, used);
break;
case BoundKind.DelegateCreationExpression:
EmitDelegateCreationExpression((BoundDelegateCreationExpression)expression, used);
break;
case BoundKind.ArrayCreation:
EmitArrayCreationExpression((BoundArrayCreation)expression, used);
break;
case BoundKind.ConvertedStackAllocExpression:
EmitConvertedStackAllocExpression((BoundConvertedStackAllocExpression)expression, used);
break;
case BoundKind.ReadOnlySpanFromArray:
EmitReadOnlySpanFromArrayExpression((BoundReadOnlySpanFromArray)expression, used);
break;
case BoundKind.Conversion:
EmitConversionExpression((BoundConversion)expression, used);
break;
case BoundKind.Local:
EmitLocalLoad((BoundLocal)expression, used);
break;
case BoundKind.Dup:
EmitDupExpression((BoundDup)expression, used);
break;
case BoundKind.PassByCopy:
EmitExpression(((BoundPassByCopy)expression).Expression, used);
break;
case BoundKind.Parameter:
if (used) // unused parameter has no side-effects
{
EmitParameterLoad((BoundParameter)expression);
}
break;
case BoundKind.FieldAccess:
EmitFieldLoad((BoundFieldAccess)expression, used);
break;
case BoundKind.ArrayAccess:
EmitArrayElementLoad((BoundArrayAccess)expression, used);
break;
case BoundKind.ArrayLength:
EmitArrayLength((BoundArrayLength)expression, used);
break;
case BoundKind.ThisReference:
if (used) // unused this has no side-effects
{
EmitThisReferenceExpression((BoundThisReference)expression);
}
break;
case BoundKind.PreviousSubmissionReference:
// Script references are lowered to a this reference and a field access.
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
case BoundKind.BaseReference:
if (used) // unused base has no side-effects
{
var thisType = _method.ContainingType;
_builder.EmitOpCode(ILOpCode.Ldarg_0);
if (thisType.IsValueType)
{
EmitLoadIndirect(thisType, expression.Syntax);
EmitBox(thisType, expression.Syntax);
}
}
break;
case BoundKind.Sequence:
EmitSequenceExpression((BoundSequence)expression, used);
break;
case BoundKind.SequencePointExpression:
EmitSequencePointExpression((BoundSequencePointExpression)expression, used);
break;
case BoundKind.UnaryOperator:
EmitUnaryOperatorExpression((BoundUnaryOperator)expression, used);
break;
case BoundKind.BinaryOperator:
EmitBinaryOperatorExpression((BoundBinaryOperator)expression, used);
break;
case BoundKind.NullCoalescingOperator:
EmitNullCoalescingOperator((BoundNullCoalescingOperator)expression, used);
break;
case BoundKind.IsOperator:
EmitIsExpression((BoundIsOperator)expression, used);
break;
case BoundKind.AsOperator:
EmitAsExpression((BoundAsOperator)expression, used);
break;
case BoundKind.DefaultExpression:
EmitDefaultExpression((BoundDefaultExpression)expression, used);
break;
case BoundKind.TypeOfOperator:
if (used) // unused typeof has no side-effects
{
EmitTypeOfExpression((BoundTypeOfOperator)expression);
}
break;
case BoundKind.SizeOfOperator:
if (used) // unused sizeof has no side-effects
{
EmitSizeOfExpression((BoundSizeOfOperator)expression);
}
break;
case BoundKind.ModuleVersionId:
Debug.Assert(used);
EmitModuleVersionIdLoad((BoundModuleVersionId)expression);
break;
case BoundKind.ModuleVersionIdString:
Debug.Assert(used);
EmitModuleVersionIdStringLoad((BoundModuleVersionIdString)expression);
break;
case BoundKind.InstrumentationPayloadRoot:
Debug.Assert(used);
EmitInstrumentationPayloadRootLoad((BoundInstrumentationPayloadRoot)expression);
break;
case BoundKind.MethodDefIndex:
Debug.Assert(used);
EmitMethodDefIndexExpression((BoundMethodDefIndex)expression);
break;
case BoundKind.MaximumMethodDefIndex:
Debug.Assert(used);
EmitMaximumMethodDefIndexExpression((BoundMaximumMethodDefIndex)expression);
break;
case BoundKind.SourceDocumentIndex:
Debug.Assert(used);
EmitSourceDocumentIndex((BoundSourceDocumentIndex)expression);
break;
case BoundKind.MethodInfo:
if (used)
{
EmitMethodInfoExpression((BoundMethodInfo)expression);
}
break;
case BoundKind.FieldInfo:
if (used)
{
EmitFieldInfoExpression((BoundFieldInfo)expression);
}
break;
case BoundKind.ConditionalOperator:
EmitConditionalOperator((BoundConditionalOperator)expression, used);
break;
case BoundKind.AddressOfOperator:
EmitAddressOfExpression((BoundAddressOfOperator)expression, used);
break;
case BoundKind.PointerIndirectionOperator:
EmitPointerIndirectionOperator((BoundPointerIndirectionOperator)expression, used);
break;
case BoundKind.ArgList:
EmitArgList(used);
break;
case BoundKind.ArgListOperator:
Debug.Assert(used);
EmitArgListOperator((BoundArgListOperator)expression);
break;
case BoundKind.RefTypeOperator:
EmitRefTypeOperator((BoundRefTypeOperator)expression, used);
break;
case BoundKind.MakeRefOperator:
EmitMakeRefOperator((BoundMakeRefOperator)expression, used);
break;
case BoundKind.RefValueOperator:
EmitRefValueOperator((BoundRefValueOperator)expression, used);
break;
case BoundKind.LoweredConditionalAccess:
EmitLoweredConditionalAccessExpression((BoundLoweredConditionalAccess)expression, used);
break;
case BoundKind.ConditionalReceiver:
EmitConditionalReceiver((BoundConditionalReceiver)expression, used);
break;
case BoundKind.ComplexConditionalReceiver:
EmitComplexConditionalReceiver((BoundComplexConditionalReceiver)expression, used);
break;
case BoundKind.PseudoVariable:
EmitPseudoVariableValue((BoundPseudoVariable)expression, used);
break;
case BoundKind.ThrowExpression:
EmitThrowExpression((BoundThrowExpression)expression, used);
break;
case BoundKind.FunctionPointerInvocation:
EmitCalli((BoundFunctionPointerInvocation)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.FunctionPointerLoad:
EmitLoadFunction((BoundFunctionPointerLoad)expression, used);
break;
default:
// Code gen should not be invoked if there are errors.
Debug.Assert(expression.Kind != BoundKind.BadExpression);
// node should have been lowered:
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
}
}
private void EmitThrowExpression(BoundThrowExpression node, bool used)
{
this.EmitThrow(node.Expression);
// to satisfy invariants, we push a default value to pretend to adjust the stack height
EmitDefaultValue(node.Type, used, node.Syntax);
}
private void EmitComplexConditionalReceiver(BoundComplexConditionalReceiver expression, bool used)
{
Debug.Assert(!expression.Type.IsReferenceType);
Debug.Assert(!expression.Type.IsValueType);
var receiverType = expression.Type;
var whenValueTypeLabel = new object();
var doneLabel = new object();
EmitInitObj(receiverType, true, expression.Syntax);
EmitBox(receiverType, expression.Syntax);
_builder.EmitBranch(ILOpCode.Brtrue, whenValueTypeLabel);
EmitExpression(expression.ReferenceTypeReceiver, used);
_builder.EmitBranch(ILOpCode.Br, doneLabel);
_builder.AdjustStack(-1);
_builder.MarkLabel(whenValueTypeLabel);
EmitExpression(expression.ValueTypeReceiver, used);
_builder.MarkLabel(doneLabel);
}
private void EmitLoweredConditionalAccessExpression(BoundLoweredConditionalAccess expression, bool used)
{
var receiver = expression.Receiver;
var receiverType = receiver.Type;
LocalDefinition receiverTemp = null;
Debug.Assert(!receiverType.IsValueType ||
(receiverType.IsNullableType() && expression.HasValueMethodOpt != null), "conditional receiver cannot be a struct");
var receiverConstant = receiver.ConstantValue;
if (receiverConstant?.IsNull == false)
{
// const but not null, must be a reference type
Debug.Assert(receiverType.IsVerifierReference());
// receiver is a reference type, so addresskind does not matter, but we do not intend to write.
receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
EmitExpression(expression.WhenNotNull, used);
if (receiverTemp != null)
{
FreeTemp(receiverTemp);
}
return;
}
// labels
object whenNotNullLabel = new object();
object doneLabel = new object();
LocalDefinition cloneTemp = null;
var notConstrained = !receiverType.IsReferenceType && !receiverType.IsValueType;
// we need a copy if we deal with nonlocal value (to capture the value)
// or if we have a ref-constrained T (to do box just once)
// or if we deal with stack local (reads are destructive)
// or if we have default(T) (to do box just once)
var nullCheckOnCopy = LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
(receiverType.IsReferenceType && receiverType.TypeKind == TypeKind.TypeParameter) ||
(receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol));
// ===== RECEIVER
if (nullCheckOnCopy)
{
if (notConstrained)
{
// if T happens to be a value type, it could be a target of mutating calls.
receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
if (receiverTemp is null)
{
// unconstrained case needs to handle case where T is actually a struct.
// such values are never nulls
// we will emit a check for such case, but the check is really a JIT-time
// constant since JIT will know if T is a struct or not.
// if ((object)default(T) != null)
// {
// goto whenNotNull
// }
// else
// {
// temp = receiverRef
// receiverRef = ref temp
// }
EmitDefaultValue(receiverType, true, receiver.Syntax);
EmitBox(receiverType, receiver.Syntax);
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
EmitLoadIndirect(receiverType, receiver.Syntax);
cloneTemp = AllocateTemp(receiverType, receiver.Syntax);
_builder.EmitLocalStore(cloneTemp);
_builder.EmitLocalAddress(cloneTemp);
_builder.EmitLocalLoad(cloneTemp);
EmitBox(receiverType, receiver.Syntax);
// here we have loaded a ref to a temp and its boxed value { &T, O }
}
else
{
// We are calling the expression on a copy of the target anyway,
// so even if T is a struct, we don't need to make sure we call the expression on the original target.
// We currently have an address on the stack. Duplicate it, and load the value of the address.
_builder.EmitOpCode(ILOpCode.Dup);
EmitLoadIndirect(receiverType, receiver.Syntax);
EmitBox(receiverType, receiver.Syntax);
}
}
else
{
// this does not need to be writeable
// we may call "HasValue" on this, but it is not mutating
var addressKind = AddressKind.ReadOnly;
receiverTemp = EmitReceiverRef(receiver, addressKind);
_builder.EmitOpCode(ILOpCode.Dup);
// here we have loaded two copies of a reference { O, O } or {&nub, &nub}
}
}
else
{
// this does not need to be writeable.
// we may call "HasValue" on this, but it is not mutating
// besides, since we are not making a copy, the receiver is not a field,
// so it cannot be readonly, in verifier sense, anyways.
receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
// here we have loaded just { O } or {&nub}
// we have the most trivial case where we can just reload receiver when needed again
}
// ===== CONDITION
var hasValueOpt = expression.HasValueMethodOpt;
if (hasValueOpt != null)
{
Debug.Assert(receiver.Type.IsNullableType());
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
EmitSymbolToken(hasValueOpt, expression.Syntax, null);
}
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
// no longer need the temp if we are not holding a copy
if (receiverTemp != null && !nullCheckOnCopy)
{
FreeTemp(receiverTemp);
receiverTemp = null;
}
// ===== WHEN NULL
if (nullCheckOnCopy)
{
_builder.EmitOpCode(ILOpCode.Pop);
}
var whenNull = expression.WhenNullOpt;
if (whenNull == null)
{
EmitDefaultValue(expression.Type, used, expression.Syntax);
}
else
{
EmitExpression(whenNull, used);
}
_builder.EmitBranch(ILOpCode.Br, doneLabel);
// ===== WHEN NOT NULL
if (nullCheckOnCopy)
{
// notNull branch pops copy of receiver off the stack when nullCheckOnCopy
// however on the isNull branch we still have the stack as it was and need
// to adjust stack depth correspondingly.
_builder.AdjustStack(+1);
}
if (used)
{
// notNull branch pushes default on the stack when used
// however on the isNull branch we still have the stack as it was and need
// to adjust stack depth correspondingly.
_builder.AdjustStack(-1);
}
_builder.MarkLabel(whenNotNullLabel);
if (!nullCheckOnCopy)
{
Debug.Assert(receiverTemp == null);
// receiver may be used as target of a struct call (if T happens to be a struct)
receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
Debug.Assert(receiverTemp == null || receiver.IsDefaultValue());
}
EmitExpression(expression.WhenNotNull, used);
// ===== DONE
_builder.MarkLabel(doneLabel);
if (cloneTemp != null)
{
FreeTemp(cloneTemp);
}
if (receiverTemp != null)
{
FreeTemp(receiverTemp);
}
}
private void EmitConditionalReceiver(BoundConditionalReceiver expression, bool used)
{
Debug.Assert(!expression.Type.IsValueType);
if (!expression.Type.IsReferenceType)
{
EmitLoadIndirect(expression.Type, expression.Syntax);
}
EmitPopIfUnused(used);
}
private void EmitRefValueOperator(BoundRefValueOperator expression, bool used)
{
EmitRefValueAddress(expression);
EmitLoadIndirect(expression.Type, expression.Syntax);
EmitPopIfUnused(used);
}
private void EmitMakeRefOperator(BoundMakeRefOperator expression, bool used)
{
// push address of variable
// mkrefany [Type] -- takes address off stack, puts TypedReference on stack
var temp = EmitAddress(expression.Operand, AddressKind.Writeable);
Debug.Assert(temp == null, "makeref should not create temps");
_builder.EmitOpCode(ILOpCode.Mkrefany);
EmitSymbolToken(expression.Operand.Type, expression.Operand.Syntax);
EmitPopIfUnused(used);
}
private void EmitRefTypeOperator(BoundRefTypeOperator expression, bool used)
{
// push TypedReference
// refanytype -- takes TypedReference off stack, puts token on stack
// call GetTypeFromHandle -- takes token off stack, puts Type on stack
EmitExpression(expression.Operand, true);
_builder.EmitOpCode(ILOpCode.Refanytype);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
var getTypeMethod = expression.GetTypeFromHandle;
Debug.Assert((object)getTypeMethod != null);
EmitSymbolToken(getTypeMethod, expression.Syntax, null);
EmitPopIfUnused(used);
}
private void EmitArgList(bool used)
{
_builder.EmitOpCode(ILOpCode.Arglist);
EmitPopIfUnused(used);
}
private void EmitArgListOperator(BoundArgListOperator expression)
{
for (int i = 0; i < expression.Arguments.Length; i++)
{
BoundExpression argument = expression.Arguments[i];
RefKind refKind = expression.ArgumentRefKindsOpt.IsDefaultOrEmpty ? RefKind.None : expression.ArgumentRefKindsOpt[i];
EmitArgument(argument, refKind);
}
}
private void EmitArgument(BoundExpression argument, RefKind refKind)
{
switch (refKind)
{
case RefKind.None:
EmitExpression(argument, true);
break;
case RefKind.In:
var temp = EmitAddress(argument, AddressKind.ReadOnly);
AddExpressionTemp(temp);
break;
default:
// NOTE: passing "ReadOnlyStrict" here.
// we should not get an address of a copy if at all possible
var unexpectedTemp = EmitAddress(argument, refKind == RefKindExtensions.StrictIn ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
if (unexpectedTemp != null)
{
// interestingly enough "ref dynamic" sometimes is passed via a clone
Debug.Assert(argument.Type.IsDynamic(), "passing args byref should not clone them into temps");
AddExpressionTemp(unexpectedTemp);
}
break;
}
}
private void EmitAddressOfExpression(BoundAddressOfOperator expression, bool used)
{
// NOTE: passing "ReadOnlyStrict" here.
// we should not get an address of a copy if at all possible
var temp = EmitAddress(expression.Operand, AddressKind.ReadOnlyStrict);
Debug.Assert(temp == null, "If the operand is addressable, then a temp shouldn't be required.");
if (used && !expression.IsManaged)
{
// When computing an address to be used to initialize a fixed-statement variable, we have to be careful
// not to convert the managed reference to an unmanaged pointer before storing it. Otherwise the GC might
// come along and move memory around, invalidating the pointer before it is pinned by being stored in
// the fixed variable. But elsewhere in the code we do use a conv.u instruction to convert the managed
// reference to the underlying type for unmanaged pointers, which is the type "unsigned int" (see CLI
// standard, Partition I section 12.1.1.1).
_builder.EmitOpCode(ILOpCode.Conv_u);
}
EmitPopIfUnused(used);
}
private void EmitPointerIndirectionOperator(BoundPointerIndirectionOperator expression, bool used)
{
EmitExpression(expression.Operand, used: true);
EmitLoadIndirect(expression.Type, expression.Syntax);
EmitPopIfUnused(used);
}
private void EmitDupExpression(BoundDup expression, bool used)
{
if (expression.RefKind == RefKind.None)
{
// unused dup is noop
if (used)
{
_builder.EmitOpCode(ILOpCode.Dup);
}
}
else
{
_builder.EmitOpCode(ILOpCode.Dup);
// must read in case if it is a null ref
EmitLoadIndirect(expression.Type, expression.Syntax);
EmitPopIfUnused(used);
}
}
private void EmitDelegateCreationExpression(BoundDelegateCreationExpression expression, bool used)
{
var mg = expression.Argument as BoundMethodGroup;
var receiver = mg != null ? mg.ReceiverOpt : expression.Argument;
var meth = expression.MethodOpt ?? receiver.Type.DelegateInvokeMethod();
Debug.Assert((object)meth != null);
EmitDelegateCreation(expression, receiver, expression.IsExtensionMethod, meth, expression.Type, used);
}
private void EmitThisReferenceExpression(BoundThisReference thisRef)
{
var thisType = thisRef.Type;
Debug.Assert(thisType.TypeKind != TypeKind.TypeParameter);
_builder.EmitOpCode(ILOpCode.Ldarg_0);
if (thisType.IsValueType)
{
EmitLoadIndirect(thisType, thisRef.Syntax);
}
}
private void EmitPseudoVariableValue(BoundPseudoVariable expression, bool used)
{
EmitExpression(expression.EmitExpressions.GetValue(expression, _diagnostics), used);
}
private void EmitSequencePointExpression(BoundSequencePointExpression node, bool used)
{
EmitSequencePoint(node);
// used is true to ensure that something is emitted
EmitExpression(node.Expression, used: true);
EmitPopIfUnused(used);
}
private void EmitSequencePoint(BoundSequencePointExpression node)
{
var syntax = node.Syntax;
if (_emitPdbSequencePoints)
{
if (syntax == null)
{
EmitHiddenSequencePoint();
}
else
{
EmitSequencePoint(syntax);
}
}
}
private void EmitSequenceExpression(BoundSequence sequence, bool used)
{
DefineLocals(sequence);
EmitSideEffects(sequence);
// CONSIDER: LocalRewriter.RewriteNestedObjectOrCollectionInitializerExpression may create a bound sequence with an unused BoundTypeExpression as the value,
// CONSIDER: which must be ignored by codegen. See comments in RewriteNestedObjectOrCollectionInitializerExpression for details and an example.
// CONSIDER: We may want to instead consider making the Value field of BoundSequence node optional to allow a sequence with
// CONSIDER: only side effects and no value. Note that VB's BoundSequence node has an optional value field.
// CONSIDER: This will allow us to remove the below check before emitting the value.
Debug.Assert(sequence.Value.Kind != BoundKind.TypeExpression || !used);
if (sequence.Value.Kind != BoundKind.TypeExpression)
{
EmitExpression(sequence.Value, used);
}
// sequence is used as a value, can release all locals
FreeLocals(sequence);
}
private void DefineLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.OpenLocalScope();
foreach (var local in sequence.Locals)
{
DefineLocal(local, sequence.Syntax);
}
}
private void FreeLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.CloseLocalScope();
foreach (var local in sequence.Locals)
{
FreeLocal(local);
}
}
/// <summary>
/// Defines sequence locals and record them so that they could be retained for the duration of the encompassing expression
/// Use this when taking a reference of the sequence, which can indirectly refer to any of its locals.
/// </summary>
private void DefineAndRecordLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.OpenLocalScope();
foreach (var local in sequence.Locals)
{
var seqLocal = DefineLocal(local, sequence.Syntax);
AddExpressionTemp(seqLocal);
}
}
/// <summary>
/// Closes the visibility/debug scopes for the sequence locals, but keep the local slots from reuse
/// for the duration of the encompassing expression.
/// Use this paired with DefineAndRecordLocals when taking a reference of the sequence, which can indirectly refer to any of its locals.
/// </summary>
private void CloseScopeAndKeepLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.CloseLocalScope();
}
private void EmitSideEffects(BoundSequence sequence)
{
var sideEffects = sequence.SideEffects;
if (!sideEffects.IsDefaultOrEmpty)
{
foreach (var se in sideEffects)
{
EmitExpression(se, false);
}
}
}
private void EmitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt)
{
// We might have an extra argument for the __arglist() of a varargs method.
Debug.Assert(arguments.Length == parameters.Length || arguments.Length == parameters.Length + 1, "argument count must match parameter count");
Debug.Assert(parameters.All(p => p.RefKind == RefKind.None) || !argRefKindsOpt.IsDefault, "there are nontrivial parameters, so we must have argRefKinds");
Debug.Assert(argRefKindsOpt.IsDefault || argRefKindsOpt.Length == arguments.Length, "if we have argRefKinds, we should have one for each argument");
for (int i = 0; i < arguments.Length; i++)
{
RefKind argRefKind = GetArgumentRefKind(arguments, parameters, argRefKindsOpt, i);
EmitArgument(arguments[i], argRefKind);
}
}
/// <summary>
/// Computes the desired refkind of the argument.
/// Considers all the cases - where ref kinds are explicit, omitted, vararg cases.
/// </summary>
internal static RefKind GetArgumentRefKind(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt, int i)
{
RefKind argRefKind;
if (i < parameters.Length)
{
if (!argRefKindsOpt.IsDefault && i < argRefKindsOpt.Length)
{
// if we have an explicit refKind for the given argument, use that
argRefKind = argRefKindsOpt[i];
Debug.Assert(argRefKind == parameters[i].RefKind ||
argRefKind == RefKindExtensions.StrictIn && parameters[i].RefKind == RefKind.In,
"in Emit the argument RefKind must be compatible with the corresponding parameter");
}
else
{
// otherwise fallback to the refKind of the parameter
argRefKind = parameters[i].RefKind;
}
}
else
{
// vararg case
Debug.Assert(arguments[i].Kind == BoundKind.ArgListOperator);
argRefKind = RefKind.None;
}
return argRefKind;
}
private void EmitArrayElementLoad(BoundArrayAccess arrayAccess, bool used)
{
EmitExpression(arrayAccess.Expression, used: true);
EmitArrayIndices(arrayAccess.Indices);
if (((ArrayTypeSymbol)arrayAccess.Expression.Type).IsSZArray)
{
var elementType = arrayAccess.Type;
if (elementType.IsEnumType())
{
//underlying primitives do not need type tokens.
elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
}
switch (elementType.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Int8:
_builder.EmitOpCode(ILOpCode.Ldelem_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Ldelem_u1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int16:
_builder.EmitOpCode(ILOpCode.Ldelem_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Ldelem_u2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
_builder.EmitOpCode(ILOpCode.Ldelem_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Ldelem_u4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Ldelem_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Ldelem_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Ldelem_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Ldelem_r8);
break;
default:
if (elementType.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Ldelem_ref);
}
else
{
if (used)
{
_builder.EmitOpCode(ILOpCode.Ldelem);
}
else
{
// no need to read whole element of nontrivial type/size here
// just take a reference to an element for array access side-effects
if (elementType.TypeKind == TypeKind.TypeParameter)
{
_builder.EmitOpCode(ILOpCode.Readonly);
}
_builder.EmitOpCode(ILOpCode.Ldelema);
}
EmitSymbolToken(elementType, arrayAccess.Syntax);
}
break;
}
}
else
{
_builder.EmitArrayElementLoad(_module.Translate((ArrayTypeSymbol)arrayAccess.Expression.Type), arrayAccess.Expression.Syntax, _diagnostics);
}
EmitPopIfUnused(used);
}
private void EmitFieldLoad(BoundFieldAccess fieldAccess, bool used)
{
var field = fieldAccess.FieldSymbol;
if (!used)
{
// fetching unused captured frame is a no-op (like reading "this")
if (field.IsCapturedFrame)
{
return;
}
// Accessing a volatile field is sideeffecting because it establishes an acquire fence.
// Otherwise, accessing an unused instance field on a struct is a noop. Just emit an unused receiver.
if (!field.IsVolatile && !field.IsStatic && fieldAccess.ReceiverOpt.Type.IsVerifierValue())
{
EmitExpression(fieldAccess.ReceiverOpt, used: false);
return;
}
}
Debug.Assert(!field.IsConst || field.ContainingType.SpecialType == SpecialType.System_Decimal,
"rewriter should lower constant fields into constant expressions");
// static field access is sideeffecting since it guarantees that ..ctor has run.
// we emit static accesses even if unused.
if (field.IsStatic)
{
if (field.IsVolatile)
{
_builder.EmitOpCode(ILOpCode.Volatile);
}
_builder.EmitOpCode(ILOpCode.Ldsfld);
EmitSymbolToken(field, fieldAccess.Syntax);
}
else
{
var receiver = fieldAccess.ReceiverOpt;
TypeSymbol fieldType = field.Type;
if (fieldType.IsValueType && (object)fieldType == (object)receiver.Type)
{
//Handle emitting a field of a self-containing struct (only possible in mscorlib)
//since "val.field" is the same as val, we only need to emit val.
EmitExpression(receiver, used);
}
else
{
var temp = EmitFieldLoadReceiver(receiver);
if (temp != null)
{
Debug.Assert(FieldLoadMustUseRef(receiver), "only clr-ambiguous structs use temps here");
FreeTemp(temp);
}
if (field.IsVolatile)
{
_builder.EmitOpCode(ILOpCode.Volatile);
}
_builder.EmitOpCode(ILOpCode.Ldfld);
EmitSymbolToken(field, fieldAccess.Syntax);
}
}
EmitPopIfUnused(used);
}
private LocalDefinition EmitFieldLoadReceiver(BoundExpression receiver)
{
// ldfld can work with structs directly or with their addresses
// accessing via address is typically same or cheaper, but not for homeless values, obviously
// there are also cases where we must emit receiver as a reference
if (FieldLoadMustUseRef(receiver) || FieldLoadPrefersRef(receiver))
{
return EmitFieldLoadReceiverAddress(receiver) ? null : EmitReceiverRef(receiver, AddressKind.ReadOnly);
}
EmitExpression(receiver, true);
return null;
}
// In special case of loading the sequence of field accesses we can perform all the
// necessary field loads using the following IL:
//
// <expr>.a.b...y.z
// |
// V
// Unbox -or- Load.Ref (<expr>)
// Ldflda a
// Ldflda b
// ...
// Ldflda y
// Ldfld z
//
// Returns 'true' if the receiver was actually emitted this way
private bool EmitFieldLoadReceiverAddress(BoundExpression receiver)
{
if (receiver == null || !receiver.Type.IsValueType)
{
return false;
}
else if (receiver.Kind == BoundKind.Conversion)
{
var conversion = (BoundConversion)receiver;
if (conversion.ConversionKind == ConversionKind.Unboxing)
{
EmitExpression(conversion.Operand, true);
_builder.EmitOpCode(ILOpCode.Unbox);
EmitSymbolToken(receiver.Type, receiver.Syntax);
return true;
}
}
else if (receiver.Kind == BoundKind.FieldAccess)
{
var fieldAccess = (BoundFieldAccess)receiver;
var field = fieldAccess.FieldSymbol;
if (!field.IsStatic && EmitFieldLoadReceiverAddress(fieldAccess.ReceiverOpt))
{
Debug.Assert(!field.IsVolatile, "volatile valuetype fields are unexpected");
_builder.EmitOpCode(ILOpCode.Ldflda);
EmitSymbolToken(field, fieldAccess.Syntax);
return true;
}
}
return false;
}
// ldfld can work with structs directly or with their addresses
// In some cases it results in same native code emitted, but in some cases JIT pushes values for real
// resulting in much worse code (on x64 in particular).
// So, we will always prefer references here except when receiver is a struct non-ref local or parameter.
private bool FieldLoadPrefersRef(BoundExpression receiver)
{
// only fields of structs can be accessed via value
if (!receiver.Type.IsVerifierValue())
{
return true;
}
// can unbox directly into a ref.
if (receiver.Kind == BoundKind.Conversion && ((BoundConversion)receiver).ConversionKind == ConversionKind.Unboxing)
{
return true;
}
// can we take address at all?
if (!HasHome(receiver, AddressKind.ReadOnly))
{
return false;
}
switch (receiver.Kind)
{
case BoundKind.Parameter:
// prefer ldarg over ldarga
return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;
case BoundKind.Local:
// prefer ldloc over ldloca
return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;
case BoundKind.Sequence:
return FieldLoadPrefersRef(((BoundSequence)receiver).Value);
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)receiver;
if (fieldAccess.FieldSymbol.IsStatic)
{
return true;
}
if (DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
{
return false;
}
return FieldLoadPrefersRef(fieldAccess.ReceiverOpt);
}
return true;
}
internal static bool FieldLoadMustUseRef(BoundExpression expr)
{
var type = expr.Type;
// type parameter values must be boxed to get access to fields
if (type.IsTypeParameter())
{
return true;
}
// From Dev12/symbol.cpp
//
// // Used by ILGEN to determine if the type of this AggregateSymbol is one that the CLR
// // will consider ambiguous to an unmanaged pointer when it is on the stack (see VSW #396011)
// bool AggregateSymbol::IsCLRAmbigStruct()
// . . .
switch (type.SpecialType)
{
// case PT_BYTE:
case SpecialType.System_Byte:
// case PT_SHORT:
case SpecialType.System_Int16:
// case PT_INT:
case SpecialType.System_Int32:
// case PT_LONG:
case SpecialType.System_Int64:
// case PT_CHAR:
case SpecialType.System_Char:
// case PT_BOOL:
case SpecialType.System_Boolean:
// case PT_SBYTE:
case SpecialType.System_SByte:
// case PT_USHORT:
case SpecialType.System_UInt16:
// case PT_UINT:
case SpecialType.System_UInt32:
// case PT_ULONG:
case SpecialType.System_UInt64:
// case PT_INTPTR:
case SpecialType.System_IntPtr:
// case PT_UINTPTR:
case SpecialType.System_UIntPtr:
// case PT_FLOAT:
case SpecialType.System_Single:
// case PT_DOUBLE:
case SpecialType.System_Double:
// case PT_TYPEHANDLE:
case SpecialType.System_RuntimeTypeHandle:
// case PT_FIELDHANDLE:
case SpecialType.System_RuntimeFieldHandle:
// case PT_METHODHANDLE:
case SpecialType.System_RuntimeMethodHandle:
//case PT_ARGUMENTHANDLE:
case SpecialType.System_RuntimeArgumentHandle:
return true;
}
// this is for value__
// I do not know how to hit this, since value__ is not bindable in C#, but Dev12 has code to handle this
return type.IsEnumType();
}
private static int ParameterSlot(BoundParameter parameter)
{
var sym = parameter.ParameterSymbol;
int slot = sym.Ordinal;
if (!sym.ContainingSymbol.IsStatic)
{
slot++; // skip "this"
}
return slot;
}
private void EmitLocalLoad(BoundLocal local, bool used)
{
if (IsStackLocal(local.LocalSymbol))
{
// local must be already on the stack
EmitPopIfUnused(used);
}
else
{
if (used)
{
LocalDefinition definition = GetLocal(local);
_builder.EmitLocalLoad(definition);
}
else
{
// do nothing. Unused local load has no side-effects.
return;
}
}
if (used && local.LocalSymbol.RefKind != RefKind.None)
{
EmitLoadIndirect(local.LocalSymbol.Type, local.Syntax);
}
}
private void EmitParameterLoad(BoundParameter parameter)
{
int slot = ParameterSlot(parameter);
_builder.EmitLoadArgumentOpcode(slot);
if (parameter.ParameterSymbol.RefKind != RefKind.None)
{
var parameterType = parameter.ParameterSymbol.Type;
EmitLoadIndirect(parameterType, parameter.Syntax);
}
}
private void EmitLoadIndirect(TypeSymbol type, SyntaxNode syntaxNode)
{
if (type.IsEnumType())
{
//underlying primitives do not need type tokens.
type = ((NamedTypeSymbol)type).EnumUnderlyingType;
}
switch (type.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Int8:
_builder.EmitOpCode(ILOpCode.Ldind_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Ldind_u1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int16:
_builder.EmitOpCode(ILOpCode.Ldind_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Ldind_u2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
_builder.EmitOpCode(ILOpCode.Ldind_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Ldind_u4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Ldind_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Ldind_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Ldind_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Ldind_r8);
break;
default:
if (type.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Ldind_ref);
}
else
{
_builder.EmitOpCode(ILOpCode.Ldobj);
EmitSymbolToken(type, syntaxNode);
}
break;
}
}
/// <summary>
/// Used to decide if we need to emit call or callvirt.
/// It basically checks if the receiver expression cannot be null, but it is not 100% precise.
/// There are cases where it really can be null, but we do not care.
/// </summary>
private bool CanUseCallOnRefTypeReceiver(BoundExpression receiver)
{
// It seems none of the ways that could produce a receiver typed as a type param
// can guarantee that it is not null.
if (receiver.Type.IsTypeParameter())
{
return false;
}
Debug.Assert(receiver.Type.IsVerifierReference(), "this is not a reference");
Debug.Assert(receiver.Kind != BoundKind.BaseReference, "base should always use call");
var constVal = receiver.ConstantValue;
if (constVal != null)
{
// only when this is a constant Null, we need a callvirt
return !constVal.IsNull;
}
switch (receiver.Kind)
{
case BoundKind.ArrayCreation:
return true;
case BoundKind.ObjectCreationExpression:
// NOTE: there are cases involving ProxyAttribute
// where newobj may produce null
return true;
case BoundKind.Conversion:
var conversion = (BoundConversion)receiver;
switch (conversion.ConversionKind)
{
case ConversionKind.Boxing:
// NOTE: boxing can produce null for Nullable, but any call through that
// will result in null reference exceptions anyways.
return true;
case ConversionKind.MethodGroup:
case ConversionKind.AnonymousFunction:
return true;
case ConversionKind.ExplicitReference:
case ConversionKind.ImplicitReference:
return CanUseCallOnRefTypeReceiver(conversion.Operand);
}
break;
case BoundKind.ThisReference:
// NOTE: these actually can be null if called from a different language
// however, we assume it is responsibility of the caller to nullcheck "this"
// if we already have access to "this", we must be in a member and should
// not redo the check
return true;
case BoundKind.FieldAccess:
// same reason as for "ThisReference"
return ((BoundFieldAccess)receiver).FieldSymbol.IsCapturedFrame;
case BoundKind.Local:
// same reason as for "ThisReference"
return ((BoundLocal)receiver).LocalSymbol.SynthesizedKind == SynthesizedLocalKind.FrameCache;
case BoundKind.DelegateCreationExpression:
return true;
case BoundKind.Sequence:
var seqValue = ((BoundSequence)(receiver)).Value;
return CanUseCallOnRefTypeReceiver(seqValue);
case BoundKind.AssignmentOperator:
var rhs = ((BoundAssignmentOperator)receiver).Right;
return CanUseCallOnRefTypeReceiver(rhs);
case BoundKind.TypeOfOperator:
return true;
case BoundKind.ConditionalReceiver:
return true;
//TODO: there could be more cases where we can be sure that receiver is not a null.
}
return false;
}
/// <summary>
/// checks if receiver is effectively ldarg.0
/// </summary>
private bool IsThisReceiver(BoundExpression receiver)
{
switch (receiver.Kind)
{
case BoundKind.ThisReference:
return true;
case BoundKind.Sequence:
var seqValue = ((BoundSequence)(receiver)).Value;
return IsThisReceiver(seqValue);
}
return false;
}
private enum CallKind
{
Call,
CallVirt,
ConstrainedCallVirt,
}
private void EmitCallExpression(BoundCall call, UseKind useKind)
{
if (call.Method.IsDefaultValueTypeConstructor(requireZeroInit: true))
{
EmitDefaultValueTypeConstructorCallExpression(call);
}
else if (!call.Method.RequiresInstanceReceiver)
{
EmitStaticCallExpression(call, useKind);
}
else
{
EmitInstanceCallExpression(call, useKind);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EmitDefaultValueTypeConstructorCallExpression(BoundCall call)
{
var method = call.Method;
var receiver = call.ReceiverOpt;
// Calls to the default struct constructor are emitted as initobj, rather than call.
// NOTE: constructor invocations are represented as BoundObjectCreationExpressions,
// rather than BoundCalls. This is why we can be confident that if we see a call to a
// constructor, it has this very specific form.
Debug.Assert(method.IsImplicitlyDeclared);
Debug.Assert(TypeSymbol.Equals(method.ContainingType, receiver.Type, TypeCompareKind.ConsiderEverything2));
Debug.Assert(receiver.Kind == BoundKind.ThisReference);
LocalDefinition tempOpt = EmitReceiverRef(receiver, AddressKind.Writeable);
_builder.EmitOpCode(ILOpCode.Initobj); // initobj <MyStruct>
EmitSymbolToken(method.ContainingType, call.Syntax);
FreeOptTemp(tempOpt);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EmitStaticCallExpression(BoundCall call, UseKind useKind)
{
var method = call.Method;
var receiver = call.ReceiverOpt;
var arguments = call.Arguments;
Debug.Assert(method.IsStatic);
EmitArguments(arguments, method.Parameters, call.ArgumentRefKindsOpt);
int stackBehavior = GetCallStackBehavior(method, arguments);
if (method.IsAbstract)
{
if (receiver is not BoundTypeExpression { Type: { TypeKind: TypeKind.TypeParameter } })
{
throw ExceptionUtilities.Unreachable;
}
_builder.EmitOpCode(ILOpCode.Constrained);
EmitSymbolToken(receiver.Type, receiver.Syntax);
}
_builder.EmitOpCode(ILOpCode.Call, stackBehavior);
EmitSymbolToken(method, call.Syntax,
method.IsVararg ? (BoundArgListOperator)arguments[arguments.Length - 1] : null);
EmitCallCleanup(call.Syntax, useKind, method);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EmitInstanceCallExpression(BoundCall call, UseKind useKind)
{
var method = call.Method;
var receiver = call.ReceiverOpt;
var arguments = call.Arguments;
LocalDefinition tempOpt = null;
Debug.Assert(!method.IsStatic && method.RequiresInstanceReceiver);
CallKind callKind;
var receiverType = receiver.Type;
if (receiverType.IsVerifierReference())
{
EmitExpression(receiver, used: true);
// In some cases CanUseCallOnRefTypeReceiver returns true which means that
// null check is unnecessary and we can use "call"
if (receiver.SuppressVirtualCalls ||
(!method.IsMetadataVirtual() && CanUseCallOnRefTypeReceiver(receiver)))
{
callKind = CallKind.Call;
}
else
{
callKind = CallKind.CallVirt;
}
}
else if (receiverType.IsVerifierValue())
{
NamedTypeSymbol methodContainingType = method.ContainingType;
if (methodContainingType.IsVerifierValue())
{
// if method is defined in the struct itself it is assumed to be mutating, unless
// it is a member of a readonly struct and is not a constructor
var receiverAddresskind = IsReadOnlyCall(method, methodContainingType) ?
AddressKind.ReadOnly :
AddressKind.Writeable;
if (MayUseCallForStructMethod(method))
{
// NOTE: this should be either a method which overrides some abstract method or
// does not override anything (with few exceptions, see MayUseCallForStructMethod);
// otherwise we should not use direct 'call' and must use constrained call;
// calling a method defined in a value type
Debug.Assert(TypeSymbol.Equals(receiverType, methodContainingType, TypeCompareKind.ObliviousNullableModifierMatchesAny));
tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
callKind = CallKind.Call;
}
else
{
tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
callKind = CallKind.ConstrainedCallVirt;
}
}
else
{
// calling a method defined in a base class.
// When calling a method that is virtual in metadata on a struct receiver,
// we use a constrained virtual call. If possible, it will skip boxing.
if (method.IsMetadataVirtual())
{
// NB: all methods that a struct could inherit from bases are non-mutating
// treat receiver as ReadOnly
tempOpt = EmitReceiverRef(receiver, AddressKind.ReadOnly);
callKind = CallKind.ConstrainedCallVirt;
}
else
{
EmitExpression(receiver, used: true);
EmitBox(receiverType, receiver.Syntax);
callKind = CallKind.Call;
}
}
}
else
{
// receiver is generic and method must come from the base or an interface or a generic constraint
// if the receiver is actually a value type it would need to be boxed.
// let .constrained sort this out.
callKind = receiverType.IsReferenceType && !IsRef(receiver) ?
CallKind.CallVirt :
CallKind.ConstrainedCallVirt;
tempOpt = EmitReceiverRef(receiver, callKind == CallKind.ConstrainedCallVirt ? AddressKind.Constrained : AddressKind.Writeable);
}
// When emitting a callvirt to a virtual method we always emit the method info of the
// method that first declared the virtual method, not the method info of an
// overriding method. It would be a subtle breaking change to change that rule;
// see bug 6156 for details.
MethodSymbol actualMethodTargetedByTheCall = method;
if (method.IsOverride && callKind != CallKind.Call)
{
actualMethodTargetedByTheCall = method.GetConstructedLeastOverriddenMethod(_method.ContainingType, requireSameReturnType: true);
}
if (callKind == CallKind.ConstrainedCallVirt && actualMethodTargetedByTheCall.ContainingType.IsValueType)
{
// special case for overridden methods like ToString(...) called on
// value types: if the original method used in emit cannot use callvirt in this
// case, change it to Call.
callKind = CallKind.Call;
}
// Devirtualizing of calls to effectively sealed methods.
if (callKind == CallKind.CallVirt)
{
// NOTE: we check that we call method in same module just to be sure
// that it cannot be recompiled as not final and make our call not verifiable.
// such change by adversarial user would arguably be a compat break, but better be safe...
// In reality we would typically have one method calling another method in the same class (one GetEnumerator calling another).
// Other scenarios are uncommon since base class cannot be sealed and
// referring to a derived type in a different module is not an easy thing to do.
if (IsThisReceiver(receiver) && actualMethodTargetedByTheCall.ContainingType.IsSealed &&
(object)actualMethodTargetedByTheCall.ContainingModule == (object)_method.ContainingModule)
{
// special case for target is in a sealed class and "this" receiver.
Debug.Assert(receiver.Type.IsVerifierReference());
callKind = CallKind.Call;
}
// NOTE: we do not check that we call method in same module.
// Because of the "GetOriginalConstructedOverriddenMethod" above, the actual target
// can only be final when it is "newslot virtual final".
// In such case Dev11 emits "call" and we will just replicate the behavior. (see DevDiv: 546853 )
else if (actualMethodTargetedByTheCall.IsMetadataFinal && CanUseCallOnRefTypeReceiver(receiver))
{
// special case for calling 'final' virtual method on reference receiver
Debug.Assert(receiver.Type.IsVerifierReference());
callKind = CallKind.Call;
}
}
EmitArguments(arguments, method.Parameters, call.ArgumentRefKindsOpt);
int stackBehavior = GetCallStackBehavior(method, arguments);
switch (callKind)
{
case CallKind.Call:
_builder.EmitOpCode(ILOpCode.Call, stackBehavior);
break;
case CallKind.CallVirt:
_builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
break;
case CallKind.ConstrainedCallVirt:
_builder.EmitOpCode(ILOpCode.Constrained);
EmitSymbolToken(receiver.Type, receiver.Syntax);
_builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
break;
}
EmitSymbolToken(actualMethodTargetedByTheCall, call.Syntax,
actualMethodTargetedByTheCall.IsVararg ? (BoundArgListOperator)arguments[arguments.Length - 1] : null);
EmitCallCleanup(call.Syntax, useKind, method);
FreeOptTemp(tempOpt);
}
private bool IsReadOnlyCall(MethodSymbol method, NamedTypeSymbol methodContainingType)
{
Debug.Assert(methodContainingType.IsVerifierValue(), "only struct calls can be readonly");
if (method.IsEffectivelyReadOnly && method.MethodKind != MethodKind.Constructor)
{
return true;
}
if (methodContainingType.IsNullableType())
{
var originalMethod = method.OriginalDefinition;
if ((object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_GetValueOrDefault) ||
(object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value) ||
(object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue))
{
return true;
}
}
return false;
}
// returns true when receiver is already a ref.
// in such cases calling through a ref could be preferred over
// calling through indirectly loaded value.
private bool IsRef(BoundExpression receiver)
{
switch (receiver.Kind)
{
case BoundKind.Local:
return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;
case BoundKind.Parameter:
return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;
case BoundKind.Call:
return ((BoundCall)receiver).Method.RefKind != RefKind.None;
case BoundKind.FunctionPointerInvocation:
return ((BoundFunctionPointerInvocation)receiver).FunctionPointer.Signature.RefKind != RefKind.None;
case BoundKind.Dup:
return ((BoundDup)receiver).RefKind != RefKind.None;
case BoundKind.Sequence:
return IsRef(((BoundSequence)receiver).Value);
}
return false;
}
private static int GetCallStackBehavior(MethodSymbol method, ImmutableArray<BoundExpression> arguments)
{
int stack = 0;
if (!method.ReturnsVoid)
{
// The call puts the return value on the stack.
stack += 1;
}
if (method.RequiresInstanceReceiver)
{
// The call pops the receiver off the stack.
stack -= 1;
}
if (method.IsVararg)
{
// The call pops all the arguments, fixed and variadic.
int fixedArgCount = arguments.Length - 1;
int varArgCount = ((BoundArgListOperator)arguments[fixedArgCount]).Arguments.Length;
stack -= fixedArgCount;
stack -= varArgCount;
}
else
{
// The call pops all the arguments.
stack -= arguments.Length;
}
return stack;
}
private static int GetObjCreationStackBehavior(BoundObjectCreationExpression objCreation)
{
int stack = 0;
// Constructor puts the return value on the stack.
stack += 1;
if (objCreation.Constructor.IsVararg)
{
// Constructor pops all the arguments, fixed and variadic.
int fixedArgCount = objCreation.Arguments.Length - 1;
int varArgCount = ((BoundArgListOperator)objCreation.Arguments[fixedArgCount]).Arguments.Length;
stack -= fixedArgCount;
stack -= varArgCount;
}
else
{
// Constructor pops all the arguments.
stack -= objCreation.Arguments.Length;
}
return stack;
}
/// <summary>
/// Used to decide if we need to emit 'call' or 'callvirt' for structure method.
/// It basically checks if the method overrides any other and method's defining type
/// is not a 'special' or 'special-by-ref' type.
/// </summary>
internal static bool MayUseCallForStructMethod(MethodSymbol method)
{
Debug.Assert(method.ContainingType.IsVerifierValue(), "this is not a value type");
if (!method.IsMetadataVirtual() || method.IsStatic)
{
return true;
}
var overriddenMethod = method.OverriddenMethod;
if ((object)overriddenMethod == null || overriddenMethod.IsAbstract)
{
return true;
}
var containingType = method.ContainingType;
// overrides in structs that are special types can be called directly.
// we can assume that special types will not be removing overrides
return containingType.SpecialType != SpecialType.None;
}
/// <summary>
/// When array operation get long or ulong arguments the args should be
/// cast to native int.
/// Note that the cast is always checked.
/// </summary>
private void TreatLongsAsNative(Microsoft.Cci.PrimitiveTypeCode tc)
{
if (tc == Microsoft.Cci.PrimitiveTypeCode.Int64)
{
_builder.EmitOpCode(ILOpCode.Conv_ovf_i);
}
else if (tc == Microsoft.Cci.PrimitiveTypeCode.UInt64)
{
_builder.EmitOpCode(ILOpCode.Conv_ovf_i_un);
}
}
private void EmitArrayLength(BoundArrayLength expression, bool used)
{
// The binder recognizes Array.Length and Array.LongLength and creates BoundArrayLength for them.
//
// ArrayLength can be either
// int32 for Array.Length
// int64 for Array.LongLength
// UIntPtr for synthetic code that needs just check if length != 0 -
// this is used in "fixed(int* ptr = arr)"
Debug.Assert(expression.Type.SpecialType == SpecialType.System_Int32 ||
expression.Type.SpecialType == SpecialType.System_Int64 ||
expression.Type.SpecialType == SpecialType.System_UIntPtr);
// ldlen will null-check the expression so it must be "used"
EmitExpression(expression.Expression, used: true);
_builder.EmitOpCode(ILOpCode.Ldlen);
var typeTo = expression.Type.PrimitiveTypeCode;
// NOTE: ldlen returns native uint, but newarr takes native int, so the length value is always
// a positive native int. We can treat it as either signed or unsigned.
// We will use whatever typeTo says so we do not need to convert because of sign.
var typeFrom = typeTo.IsUnsigned() ? Microsoft.Cci.PrimitiveTypeCode.UIntPtr : Microsoft.Cci.PrimitiveTypeCode.IntPtr;
// NOTE: In Dev10 C# this cast is unchecked.
// That seems to be wrong since that would cause silent truncation on 64bit platform if that implements large arrays.
//
// Emitting checked conversion however results in redundant overflow checks on 64bit and also inhibits range check hoisting in loops.
// Therefore we will emit unchecked conversion here as C# compiler always did.
_builder.EmitNumericConversion(typeFrom, typeTo, @checked: false);
EmitPopIfUnused(used);
}
private void EmitArrayCreationExpression(BoundArrayCreation expression, bool used)
{
var arrayType = (ArrayTypeSymbol)expression.Type;
EmitArrayIndices(expression.Bounds);
if (arrayType.IsSZArray)
{
_builder.EmitOpCode(ILOpCode.Newarr);
EmitSymbolToken(arrayType.ElementType, expression.Syntax);
}
else
{
_builder.EmitArrayCreation(_module.Translate(arrayType), expression.Syntax, _diagnostics);
}
if (expression.InitializerOpt != null)
{
EmitArrayInitializers(arrayType, expression.InitializerOpt);
}
// newarr has side-effects (negative bounds etc) so always emitted.
EmitPopIfUnused(used);
}
private void EmitConvertedStackAllocExpression(BoundConvertedStackAllocExpression expression, bool used)
{
EmitExpression(expression.Count, used);
// the only sideeffect of a localloc is a nondeterministic and generally fatal StackOverflow.
// we can ignore that if the actual result is unused
if (used)
{
_sawStackalloc = true;
_builder.EmitOpCode(ILOpCode.Localloc);
}
var initializer = expression.InitializerOpt;
if (initializer != null)
{
if (used)
{
EmitStackAllocInitializers(expression.Type, initializer);
}
else
{
// If not used, just emit initializer elements to preserve possible sideeffects
foreach (var init in initializer.Initializers)
{
EmitExpression(init, used: false);
}
}
}
}
private void EmitObjectCreationExpression(BoundObjectCreationExpression expression, bool used)
{
MethodSymbol constructor = expression.Constructor;
if (constructor.IsDefaultValueTypeConstructor(requireZeroInit: true))
{
EmitInitObj(expression.Type, used, expression.Syntax);
}
else
{
// check if need to construct at all
if (!used && ConstructorNotSideEffecting(constructor))
{
// ctor has no side-effects, so we will just evaluate the arguments
foreach (var arg in expression.Arguments)
{
EmitExpression(arg, used: false);
}
return;
}
// ReadOnlySpan may just refer to the blob, if possible.
if (this._module.Compilation.IsReadOnlySpanType(expression.Type) &&
expression.Arguments.Length == 1)
{
if (TryEmitReadonlySpanAsBlobWrapper((NamedTypeSymbol)expression.Type, expression.Arguments[0], used, inPlace: false))
{
return;
}
}
// none of the above cases, so just create an instance
EmitArguments(expression.Arguments, constructor.Parameters, expression.ArgumentRefKindsOpt);
var stackAdjustment = GetObjCreationStackBehavior(expression);
_builder.EmitOpCode(ILOpCode.Newobj, stackAdjustment);
// for variadic ctors emit expanded ctor token
EmitSymbolToken(constructor, expression.Syntax,
constructor.IsVararg ? (BoundArgListOperator)expression.Arguments[expression.Arguments.Length - 1] : null);
EmitPopIfUnused(used);
}
}
/// <summary>
/// Recognizes constructors known to not have side-effects (which means they can be skipped unless the constructed object is used)
/// </summary>
private bool ConstructorNotSideEffecting(MethodSymbol constructor)
{
var originalDef = constructor.OriginalDefinition;
var compilation = _module.Compilation;
if (originalDef == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor))
{
return true;
}
if (originalDef.ContainingType.Name == NamedTypeSymbol.ValueTupleTypeName &&
(originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__ctor) ||
originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__ctor)))
{
return true;
}
return false;
}
private void EmitAssignmentExpression(BoundAssignmentOperator assignmentOperator, UseKind useKind)
{
if (TryEmitAssignmentInPlace(assignmentOperator, useKind != UseKind.Unused))
{
return;
}
// Assignment expression codegen has the following parts:
//
// * PreRHS: We need to emit instructions before the load of the right hand side if:
// - If the left hand side is a ref local or ref formal parameter and the right hand
// side is a value then we must put the ref on the stack early so that we can store
// indirectly into it.
// - If the left hand side is an array slot then we must evaluate the array and indices
// before we evaluate the right hand side. We ensure that the array and indices are
// on the stack when the store is executed.
// - Similarly, if the left hand side is a non-static field then its receiver must be
// evaluated before the right hand side.
//
// * RHS: There are three possible ways to do an assignment with respect to "refness",
// and all are found in the lowering of:
//
// N().s += 10;
//
// That expression is realized as
//
// ref int addr = ref N().s; // Assign a ref on the right hand side to the left hand side.
// int sum = addr + 10; // No refs at all; assign directly to sum.
// addr = sum; // Assigns indirectly through the address.
//
// - If we are in the first case then assignmentOperator.RefKind is Ref and the left hand side is a
// ref local temporary. We simply assign the ref on the RHS to the storage on the LHS with no indirection.
//
// - If we are in the second case then nothing is ref; we have a value on one side an a local on the other.
// Again, there is no indirection.
//
// - If we are in the third case then we have a ref on the left and a value on the right. We must compute the
// value of the right hand side and then store it into the left hand side.
//
// * Duplication: The result of an assignment operation is the value that was assigned. It is possible that
// later codegen is expecting this value to be on the stack when we're done here. This is controlled by
// the "used" formal parameter. There are two possible cases:
// - If the preamble put stuff on the stack for the usage of the store, then we must not put an extra copy
// of the right hand side value on the stack; that will be between the value and the stuff needed to
// do the storage. In that case we put the right hand side value in a temporary and restore it later.
// - Otherwise we can just do a dup instruction; there's nothing before the dup on the stack that we'll need.
//
// * Storage: Either direct or indirect, depending. See the RHS section above for details.
//
// * Post-storage: If we stashed away the duplicated value in the temporary, we need to restore it back to the stack.
bool lhsUsesStack = EmitAssignmentPreamble(assignmentOperator);
EmitAssignmentValue(assignmentOperator);
LocalDefinition temp = EmitAssignmentDuplication(assignmentOperator, useKind, lhsUsesStack);
EmitStore(assignmentOperator);
EmitAssignmentPostfix(assignmentOperator, temp, useKind);
}
// sometimes it is possible and advantageous to get an address of the lHS and
// perform assignment as an in-place initialization via initobj or constructor invocation.
//
// 1) initobj
// is used when assigning default value to T that is not a verifier reference.
//
// 2) in-place ctor call
// is used when assigning a freshly created struct. "x = new S(arg)" can be
// replaced by x.S(arg) as long as partial assignment cannot be observed -
// i.e. target must not be on the heap and we should not be in a try block.
private bool TryEmitAssignmentInPlace(BoundAssignmentOperator assignmentOperator, bool used)
{
// If the left hand is itself a ref, then we can't use in-place assignment
// because we need to spill the creation. This code can't be written in C#, but
// can be produced by lowering.
if (assignmentOperator.IsRef)
{
return false;
}
var left = assignmentOperator.Left;
// if result is used, and lives on heap, we must keep RHS value on the stack.
// otherwise we can try conjuring up the RHS value directly where it belongs.
if (used && !TargetIsNotOnHeap(left))
{
return false;
}
if (!SafeToGetWriteableReference(left))
{
// cannot take a ref
return false;
}
var right = assignmentOperator.Right;
var rightType = right.Type;
// in-place is not advantageous for reference types or constants
if (!rightType.IsTypeParameter())
{
if (rightType.IsReferenceType || (right.ConstantValue != null && rightType.SpecialType != SpecialType.System_Decimal))
{
return false;
}
}
if (right.IsDefaultValue())
{
InPlaceInit(left, used);
return true;
}
if (right is BoundObjectCreationExpression objCreation)
{
// If we are creating a Span<T> from a stackalloc, which is a particular pattern of code
// produced by lowering, we must use the constructor in its standard form because the stack
// is required to contain nothing more than stackalloc's argument.
if (objCreation.Arguments.Length > 0 && objCreation.Arguments[0].Kind == BoundKind.ConvertedStackAllocExpression)
{
return false;
}
// It is desirable to do in-place ctor call if possible.
// we could do newobj/stloc, but in-place call
// produces the same or better code in current JITs
if (PartialCtorResultCannotEscape(left))
{
var ctor = objCreation.Constructor;
// ctor can possibly see its own assignments indirectly if there are ref parameters or __arglist
if (System.Linq.ImmutableArrayExtensions.All(ctor.Parameters, p => p.RefKind == RefKind.None) &&
!ctor.IsVararg)
{
InPlaceCtorCall(left, objCreation, used);
return true;
}
}
}
return false;
}
private bool SafeToGetWriteableReference(BoundExpression left)
{
if (!HasHome(left, AddressKind.Writeable))
{
return false;
}
// because of array covariance, taking a reference to an element of
// generic array may fail even though assignment "arr[i] = default(T)" would always succeed.
if (left.Kind == BoundKind.ArrayAccess && left.Type.TypeKind == TypeKind.TypeParameter && !left.Type.IsValueType)
{
return false;
}
if (left.Kind == BoundKind.FieldAccess)
{
var fieldAccess = (BoundFieldAccess)left;
if (fieldAccess.FieldSymbol.IsVolatile ||
DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
{
return false;
}
}
return true;
}
private void InPlaceInit(BoundExpression target, bool used)
{
var temp = EmitAddress(target, AddressKind.Writeable);
Debug.Assert(temp == null, "in-place init target should not create temps");
_builder.EmitOpCode(ILOpCode.Initobj); // initobj <MyStruct>
EmitSymbolToken(target.Type, target.Syntax);
if (used)
{
Debug.Assert(TargetIsNotOnHeap(target), "cannot read-back the target since it could have been modified");
EmitExpression(target, used);
}
}
private void InPlaceCtorCall(BoundExpression target, BoundObjectCreationExpression objCreation, bool used)
{
Debug.Assert(TargetIsNotOnHeap(target), "in-place construction target should not be on heap");
var temp = EmitAddress(target, AddressKind.Writeable);
Debug.Assert(temp == null, "in-place ctor target should not create temps");
// ReadOnlySpan may just refer to the blob, if possible.
if (this._module.Compilation.IsReadOnlySpanType(objCreation.Type) && objCreation.Arguments.Length == 1)
{
if (TryEmitReadonlySpanAsBlobWrapper((NamedTypeSymbol)objCreation.Type, objCreation.Arguments[0], used, inPlace: true))
{
if (used)
{
EmitExpression(target, used: true);
}
return;
}
}
var constructor = objCreation.Constructor;
EmitArguments(objCreation.Arguments, constructor.Parameters, objCreation.ArgumentRefKindsOpt);
// -2 to adjust for consumed target address and not produced value.
var stackAdjustment = GetObjCreationStackBehavior(objCreation) - 2;
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment);
// for variadic ctors emit expanded ctor token
EmitSymbolToken(constructor, objCreation.Syntax,
constructor.IsVararg ? (BoundArgListOperator)objCreation.Arguments[objCreation.Arguments.Length - 1] : null);
if (used)
{
EmitExpression(target, used: true);
}
}
// partial ctor results are not observable when target is not on the heap.
// we also must not be in a try, otherwise if ctor throws
// partially assigned value may be observed in the handler.
private bool PartialCtorResultCannotEscape(BoundExpression left)
{
if (TargetIsNotOnHeap(left))
{
if (_tryNestingLevel != 0)
{
var local = left as BoundLocal;
if (local != null && !_builder.PossiblyDefinedOutsideOfTry(GetLocal(local)))
{
// local defined inside immediate Try - cannot escape
return true;
}
// local defined outside of immediate try or it is a parameter - can escape
return false;
}
// we are not in a try - locals, parameters cannot escape
return true;
}
// left is a reference, partial initializations can escape.
return false;
}
// returns True when assignment target is definitely not on the heap
private static bool TargetIsNotOnHeap(BoundExpression left)
{
switch (left.Kind)
{
case BoundKind.Parameter:
return ((BoundParameter)left).ParameterSymbol.RefKind == RefKind.None;
case BoundKind.Local:
// NOTE: stack locals are either homeless or refs, no need to special case them
// they will never be assigned in-place.
return ((BoundLocal)left).LocalSymbol.RefKind == RefKind.None;
}
return false;
}
private bool EmitAssignmentPreamble(BoundAssignmentOperator assignmentOperator)
{
var assignmentTarget = assignmentOperator.Left;
bool lhsUsesStack = false;
switch (assignmentTarget.Kind)
{
case BoundKind.RefValueOperator:
EmitRefValueAddress((BoundRefValueOperator)assignmentTarget);
break;
case BoundKind.FieldAccess:
{
var left = (BoundFieldAccess)assignmentTarget;
if (!left.FieldSymbol.IsStatic)
{
var temp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
Debug.Assert(temp == null, "temp is unexpected when assigning to a field");
lhsUsesStack = true;
}
}
break;
case BoundKind.Parameter:
{
var left = (BoundParameter)assignmentTarget;
if (left.ParameterSymbol.RefKind != RefKind.None &&
!assignmentOperator.IsRef)
{
_builder.EmitLoadArgumentOpcode(ParameterSlot(left));
lhsUsesStack = true;
}
}
break;
case BoundKind.Local:
{
var left = (BoundLocal)assignmentTarget;
// Again, consider our earlier case:
//
// ref int addr = ref N().s;
// int sum = addr + 10;
// addr = sum;
//
// There are three different ways we could be assigning to a local.
//
// In the first case, we want to simply call N(), take the address
// of s, and then store that address in addr.
//
// In the second case again we simply want to compute the sum and
// store the result in sum.
//
// In the third case however we want to first load the contents of
// addr -- the address of field s -- then put the sum on the stack,
// and then do an indirect store. In that case we need to have the
// contents of addr on the stack.
if (left.LocalSymbol.RefKind != RefKind.None && !assignmentOperator.IsRef)
{
if (!IsStackLocal(left.LocalSymbol))
{
LocalDefinition localDefinition = GetLocal(left);
_builder.EmitLocalLoad(localDefinition);
}
else
{
// this is a case of indirect assignment to a stack temp.
// currently byref temp can only be a stack local in scenarios where
// there is only one assignment and it is the last one.
// I do not yet know how to support cases where we assign more than once.
// That where Dup of LHS would be needed, but as a general scenario
// it is not always possible to handle. Fortunately all the cases where we
// indirectly assign to a byref temp come from rewriter and all
// they all are write-once cases.
//
// For now analyzer asserts that indirect writes are final reads of
// a ref local. And we never need a dup here.
// builder.EmitOpCode(ILOpCode.Dup);
}
lhsUsesStack = true;
}
}
break;
case BoundKind.ArrayAccess:
{
var left = (BoundArrayAccess)assignmentTarget;
EmitExpression(left.Expression, used: true);
EmitArrayIndices(left.Indices);
lhsUsesStack = true;
}
break;
case BoundKind.ThisReference:
{
var left = (BoundThisReference)assignmentTarget;
var temp = EmitAddress(left, AddressKind.Writeable);
Debug.Assert(temp == null, "taking ref of this should not create a temp");
lhsUsesStack = true;
}
break;
case BoundKind.Dup:
{
var left = (BoundDup)assignmentTarget;
var temp = EmitAddress(left, AddressKind.Writeable);
Debug.Assert(temp == null, "taking ref of Dup should not create a temp");
lhsUsesStack = true;
}
break;
case BoundKind.ConditionalOperator:
{
var left = (BoundConditionalOperator)assignmentTarget;
Debug.Assert(left.IsRef);
var temp = EmitAddress(left, AddressKind.Writeable);
Debug.Assert(temp == null, "taking ref of this should not create a temp");
lhsUsesStack = true;
}
break;
case BoundKind.PointerIndirectionOperator:
{
var left = (BoundPointerIndirectionOperator)assignmentTarget;
EmitExpression(left.Operand, used: true);
lhsUsesStack = true;
}
break;
case BoundKind.Sequence:
{
var sequence = (BoundSequence)assignmentTarget;
// NOTE: not releasing sequence locals right away.
// Since sequence is used as a variable, we will keep the locals for the extent of the containing expression
DefineAndRecordLocals(sequence);
EmitSideEffects(sequence);
lhsUsesStack = EmitAssignmentPreamble(assignmentOperator.Update(sequence.Value, assignmentOperator.Right, assignmentOperator.IsRef, assignmentOperator.Type));
CloseScopeAndKeepLocals(sequence);
}
break;
case BoundKind.Call:
{
var left = (BoundCall)assignmentTarget;
Debug.Assert(left.Method.RefKind != RefKind.None);
EmitCallExpression(left, UseKind.UsedAsAddress);
lhsUsesStack = true;
}
break;
case BoundKind.FunctionPointerInvocation:
{
var left = (BoundFunctionPointerInvocation)assignmentTarget;
Debug.Assert(left.FunctionPointer.Signature.RefKind != RefKind.None);
EmitCalli(left, UseKind.UsedAsAddress);
lhsUsesStack = true;
}
break;
case BoundKind.PropertyAccess:
case BoundKind.IndexerAccess:
// Property access should have been rewritten.
case BoundKind.PreviousSubmissionReference:
// Script references are lowered to a this reference and a field access.
throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);
case BoundKind.PseudoVariable:
EmitPseudoVariableAddress((BoundPseudoVariable)assignmentTarget);
lhsUsesStack = true;
break;
case BoundKind.ModuleVersionId:
case BoundKind.InstrumentationPayloadRoot:
break;
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)assignmentTarget;
if (!assignment.IsRef)
{
goto default;
}
EmitAssignmentExpression(assignment, UseKind.UsedAsAddress);
break;
default:
throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);
}
return lhsUsesStack;
}
private void EmitAssignmentValue(BoundAssignmentOperator assignmentOperator)
{
if (!assignmentOperator.IsRef)
{
EmitExpression(assignmentOperator.Right, used: true);
}
else
{
int exprTempsBefore = _expressionTemps?.Count ?? 0;
BoundExpression lhs = assignmentOperator.Left;
// NOTE: passing "ReadOnlyStrict" here.
// we should not get an address of a copy if at all possible
LocalDefinition temp = EmitAddress(assignmentOperator.Right, lhs.GetRefKind() == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
// Generally taking a ref for the purpose of ref assignment should not be done on homeless values
// however, there are very rare cases when we need to get a ref off a temp in synthetic code.
// Retain those temps for the extent of the encompassing expression.
AddExpressionTemp(temp);
var exprTempsAfter = _expressionTemps?.Count ?? 0;
// are we, by the way, ref-assigning to something that lives longer than encompassing expression?
Debug.Assert(lhs.Kind != BoundKind.Parameter || exprTempsAfter <= exprTempsBefore);
if (lhs.Kind == BoundKind.Local && ((BoundLocal)lhs).LocalSymbol.SynthesizedKind.IsLongLived())
{
// This situation is extremely rare. We are assigning a ref to a local with unknown lifetime
// while computing that ref required expression temps.
//
// We cannot reuse any of those temps and must leak them from the retained set.
// Any of them could be directly or indirectly referred by the LHS after the assignment.
// and we do not know the scope of the LHS - could be the whole method.
if (exprTempsAfter > exprTempsBefore)
{
_expressionTemps.Count = exprTempsBefore;
}
}
}
}
private LocalDefinition EmitAssignmentDuplication(BoundAssignmentOperator assignmentOperator, UseKind useKind, bool lhsUsesStack)
{
LocalDefinition temp = null;
if (useKind != UseKind.Unused)
{
_builder.EmitOpCode(ILOpCode.Dup);
if (lhsUsesStack)
{
// Today we sometimes have a case where we assign a ref directly to a temporary of ref type:
//
// ref int addr = ref N().y; <-- copies the address by value; no indirection
// int sum = addr + 10;
// addr = sum;
//
// If we have something like:
//
// ref int t1 = (ref int t2 = ref M().s);
//
// or the even more odd:
//
// int t1 = (ref int t2 = ref M().s);
//
// We need to figure out which of the situations above we are in, and ensure that the
// correct kind of temporary is created here. And also that either its value or its
// indirected value is read out after the store, in EmitAssignmentPostfix, below.
temp = AllocateTemp(
assignmentOperator.Left.Type,
assignmentOperator.Left.Syntax,
assignmentOperator.IsRef ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
_builder.EmitLocalStore(temp);
}
}
return temp;
}
private void EmitStore(BoundAssignmentOperator assignment)
{
BoundExpression expression = assignment.Left;
switch (expression.Kind)
{
case BoundKind.FieldAccess:
EmitFieldStore((BoundFieldAccess)expression);
break;
case BoundKind.Local:
// If we are doing a 'normal' local assignment like 'int t = 10;', or
// if we are initializing a temporary like 'ref int t = ref M().s;' then
// we just emit a local store. If we are doing an assignment through
// a ref local temporary then we assume that the instruction to load
// the address is already on the stack, and we must indirect through it.
// See the comments in EmitAssignmentExpression above for details.
BoundLocal local = (BoundLocal)expression;
if (local.LocalSymbol.RefKind != RefKind.None && !assignment.IsRef)
{
EmitIndirectStore(local.LocalSymbol.Type, local.Syntax);
}
else
{
if (IsStackLocal(local.LocalSymbol))
{
// assign to stack var == leave original value on stack
break;
}
else
{
_builder.EmitLocalStore(GetLocal(local));
}
}
break;
case BoundKind.ArrayAccess:
var array = ((BoundArrayAccess)expression).Expression;
var arrayType = (ArrayTypeSymbol)array.Type;
EmitArrayElementStore(arrayType, expression.Syntax);
break;
case BoundKind.ThisReference:
EmitThisStore((BoundThisReference)expression);
break;
case BoundKind.Parameter:
EmitParameterStore((BoundParameter)expression, assignment.IsRef);
break;
case BoundKind.Dup:
Debug.Assert(((BoundDup)expression).RefKind != RefKind.None);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.ConditionalOperator:
Debug.Assert(((BoundConditionalOperator)expression).IsRef);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.RefValueOperator:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PseudoVariable:
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.Sequence:
{
var sequence = (BoundSequence)expression;
EmitStore(assignment.Update(sequence.Value, assignment.Right, assignment.IsRef, assignment.Type));
}
break;
case BoundKind.Call:
Debug.Assert(((BoundCall)expression).Method.RefKind != RefKind.None);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.FunctionPointerInvocation:
Debug.Assert(((BoundFunctionPointerInvocation)expression).FunctionPointer.Signature.RefKind != RefKind.None);
EmitIndirectStore(expression.Type, expression.Syntax);
break;
case BoundKind.ModuleVersionId:
EmitModuleVersionIdStore((BoundModuleVersionId)expression);
break;
case BoundKind.InstrumentationPayloadRoot:
EmitInstrumentationPayloadRootStore((BoundInstrumentationPayloadRoot)expression);
break;
case BoundKind.AssignmentOperator:
var nested = (BoundAssignmentOperator)expression;
if (!nested.IsRef)
{
goto default;
}
EmitIndirectStore(nested.Type, expression.Syntax);
break;
case BoundKind.PreviousSubmissionReference:
// Script references are lowered to a this reference and a field access.
default:
throw ExceptionUtilities.UnexpectedValue(expression.Kind);
}
}
private void EmitAssignmentPostfix(BoundAssignmentOperator assignment, LocalDefinition temp, UseKind useKind)
{
if (temp != null)
{
if (useKind == UseKind.UsedAsAddress)
{
_builder.EmitLocalAddress(temp);
}
else
{
_builder.EmitLocalLoad(temp);
}
FreeTemp(temp);
}
if (useKind == UseKind.UsedAsValue && assignment.IsRef)
{
EmitLoadIndirect(assignment.Type, assignment.Syntax);
}
}
private void EmitThisStore(BoundThisReference thisRef)
{
Debug.Assert(thisRef.Type.IsValueType);
_builder.EmitOpCode(ILOpCode.Stobj);
EmitSymbolToken(thisRef.Type, thisRef.Syntax);
}
private void EmitArrayElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
{
if (arrayType.IsSZArray)
{
EmitVectorElementStore(arrayType, syntaxNode);
}
else
{
_builder.EmitArrayElementStore(_module.Translate(arrayType), syntaxNode, _diagnostics);
}
}
/// <summary>
/// Emit an element store instruction for a single dimensional array.
/// </summary>
private void EmitVectorElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
{
var elementType = arrayType.ElementType;
if (elementType.IsEnumType())
{
//underlying primitives do not need type tokens.
elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
}
switch (elementType.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.Int8:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Stelem_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.Int16:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Stelem_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Stelem_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Stelem_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Stelem_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Stelem_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Stelem_r8);
break;
default:
if (elementType.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Stelem_ref);
}
else
{
_builder.EmitOpCode(ILOpCode.Stelem);
EmitSymbolToken(elementType, syntaxNode);
}
break;
}
}
private void EmitFieldStore(BoundFieldAccess fieldAccess)
{
var field = fieldAccess.FieldSymbol;
if (field.IsVolatile)
{
_builder.EmitOpCode(ILOpCode.Volatile);
}
_builder.EmitOpCode(field.IsStatic ? ILOpCode.Stsfld : ILOpCode.Stfld);
EmitSymbolToken(field, fieldAccess.Syntax);
}
private void EmitParameterStore(BoundParameter parameter, bool refAssign)
{
int slot = ParameterSlot(parameter);
if (parameter.ParameterSymbol.RefKind != RefKind.None && !refAssign)
{
//NOTE: we should have the actual parameter already loaded,
//now need to do a store to where it points to
EmitIndirectStore(parameter.ParameterSymbol.Type, parameter.Syntax);
}
else
{
_builder.EmitStoreArgumentOpcode(slot);
}
}
private void EmitIndirectStore(TypeSymbol type, SyntaxNode syntaxNode)
{
if (type.IsEnumType())
{
//underlying primitives do not need type tokens.
type = ((NamedTypeSymbol)type).EnumUnderlyingType;
}
switch (type.PrimitiveTypeCode)
{
case Microsoft.Cci.PrimitiveTypeCode.Boolean:
case Microsoft.Cci.PrimitiveTypeCode.Int8:
case Microsoft.Cci.PrimitiveTypeCode.UInt8:
_builder.EmitOpCode(ILOpCode.Stind_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Char:
case Microsoft.Cci.PrimitiveTypeCode.Int16:
case Microsoft.Cci.PrimitiveTypeCode.UInt16:
_builder.EmitOpCode(ILOpCode.Stind_i2);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int32:
case Microsoft.Cci.PrimitiveTypeCode.UInt32:
_builder.EmitOpCode(ILOpCode.Stind_i4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Int64:
case Microsoft.Cci.PrimitiveTypeCode.UInt64:
_builder.EmitOpCode(ILOpCode.Stind_i8);
break;
case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
case Microsoft.Cci.PrimitiveTypeCode.Pointer:
case Microsoft.Cci.PrimitiveTypeCode.FunctionPointer:
_builder.EmitOpCode(ILOpCode.Stind_i);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float32:
_builder.EmitOpCode(ILOpCode.Stind_r4);
break;
case Microsoft.Cci.PrimitiveTypeCode.Float64:
_builder.EmitOpCode(ILOpCode.Stind_r8);
break;
default:
if (type.IsVerifierReference())
{
_builder.EmitOpCode(ILOpCode.Stind_ref);
}
else
{
_builder.EmitOpCode(ILOpCode.Stobj);
EmitSymbolToken(type, syntaxNode);
}
break;
}
}
private void EmitPopIfUnused(bool used)
{
if (!used)
{
_builder.EmitOpCode(ILOpCode.Pop);
}
}
private void EmitIsExpression(BoundIsOperator isOp, bool used)
{
var operand = isOp.Operand;
EmitExpression(operand, used);
if (used)
{
Debug.Assert((object)operand.Type != null);
if (!operand.Type.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operand.Type, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(isOp.TargetType.Type, isOp.Syntax);
_builder.EmitOpCode(ILOpCode.Ldnull);
_builder.EmitOpCode(ILOpCode.Cgt_un);
}
}
private void EmitAsExpression(BoundAsOperator asOp, bool used)
{
Debug.Assert(!asOp.Conversion.Kind.IsImplicitConversion());
var operand = asOp.Operand;
EmitExpression(operand, used);
if (used)
{
var operandType = operand.Type;
var targetType = asOp.Type;
Debug.Assert((object)targetType != null);
if ((object)operandType != null && !operandType.IsVerifierReference())
{
// box the operand for isinst if it is not a verifier reference
EmitBox(operandType, operand.Syntax);
}
_builder.EmitOpCode(ILOpCode.Isinst);
EmitSymbolToken(targetType, asOp.Syntax);
if (!targetType.IsVerifierReference())
{
// We need to unbox if the target type is not a reference type
_builder.EmitOpCode(ILOpCode.Unbox_any);
EmitSymbolToken(targetType, asOp.Syntax);
}
}
}
private void EmitDefaultValue(TypeSymbol type, bool used, SyntaxNode syntaxNode)
{
if (used)
{
// default type parameter values must be emitted as 'initobj' regardless of constraints
if (!type.IsTypeParameter() && type.SpecialType != SpecialType.System_Decimal)
{
var constantValue = type.GetDefaultValue();
if (constantValue != null)
{
_builder.EmitConstantValue(constantValue);
return;
}
}
if (type.IsPointerOrFunctionPointer() || type.SpecialType == SpecialType.System_UIntPtr)
{
// default(whatever*) and default(UIntPtr) can be emitted as:
_builder.EmitOpCode(ILOpCode.Ldc_i4_0);
_builder.EmitOpCode(ILOpCode.Conv_u);
}
else if (type.SpecialType == SpecialType.System_IntPtr)
{
_builder.EmitOpCode(ILOpCode.Ldc_i4_0);
_builder.EmitOpCode(ILOpCode.Conv_i);
}
else
{
EmitInitObj(type, true, syntaxNode);
}
}
}
private void EmitDefaultExpression(BoundDefaultExpression expression, bool used)
{
Debug.Assert(expression.Type.SpecialType == SpecialType.System_Decimal ||
expression.Type.GetDefaultValue() == null, "constant should be set on this expression");
// Default value for the given default expression is not a constant
// Expression must be of type parameter type or a non-primitive value type
// Emit an initobj instruction for these cases
EmitDefaultValue(expression.Type, used, expression.Syntax);
}
private void EmitConstantExpression(TypeSymbol type, ConstantValue constantValue, bool used, SyntaxNode syntaxNode)
{
if (used) // unused constant has no side-effects
{
// Null type parameter values must be emitted as 'initobj' rather than 'ldnull'.
if (((object)type != null) && (type.TypeKind == TypeKind.TypeParameter) && constantValue.IsNull)
{
EmitInitObj(type, used, syntaxNode);
}
else
{
_builder.EmitConstantValue(constantValue);
}
}
}
private void EmitInitObj(TypeSymbol type, bool used, SyntaxNode syntaxNode)
{
if (used)
{
var temp = this.AllocateTemp(type, syntaxNode);
_builder.EmitLocalAddress(temp); // ldloca temp
_builder.EmitOpCode(ILOpCode.Initobj); // initobj <MyStruct>
EmitSymbolToken(type, syntaxNode);
_builder.EmitLocalLoad(temp); // ldloc temp
FreeTemp(temp);
}
}
private void EmitGetTypeFromHandle(BoundTypeOf boundTypeOf)
{
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
var getTypeMethod = boundTypeOf.GetTypeFromHandle;
Debug.Assert((object)getTypeMethod != null); // Should have been checked during binding
EmitSymbolToken(getTypeMethod, boundTypeOf.Syntax, null);
}
private void EmitTypeOfExpression(BoundTypeOfOperator boundTypeOfOperator)
{
TypeSymbol type = boundTypeOfOperator.SourceType.Type;
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(type, boundTypeOfOperator.SourceType.Syntax);
EmitGetTypeFromHandle(boundTypeOfOperator);
}
private void EmitSizeOfExpression(BoundSizeOfOperator boundSizeOfOperator)
{
TypeSymbol type = boundSizeOfOperator.SourceType.Type;
_builder.EmitOpCode(ILOpCode.Sizeof);
EmitSymbolToken(type, boundSizeOfOperator.SourceType.Syntax);
}
private void EmitMethodDefIndexExpression(BoundMethodDefIndex node)
{
Debug.Assert(node.Method.IsDefinition);
Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
_builder.EmitOpCode(ILOpCode.Ldtoken);
// For partial methods, we emit pseudo token based on the symbol for the partial
// definition part as opposed to the symbol for the partial implementation part.
// We will need to resolve the symbol associated with each pseudo token in order
// to compute the real method definition tokens later. For partial methods, this
// resolution can only succeed if the associated symbol is the symbol for the
// partial definition and not the symbol for the partial implementation (see
// MethodSymbol.ResolvedMethodImpl()).
var symbol = node.Method.PartialDefinitionPart ?? node.Method;
EmitSymbolToken(symbol, node.Syntax, null, encodeAsRawDefinitionToken: true);
}
private void EmitMaximumMethodDefIndexExpression(BoundMaximumMethodDefIndex node)
{
Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
_builder.EmitOpCode(ILOpCode.Ldtoken);
_builder.EmitGreatestMethodToken();
}
private void EmitModuleVersionIdLoad(BoundModuleVersionId node)
{
_builder.EmitOpCode(ILOpCode.Ldsfld);
EmitModuleVersionIdToken(node);
}
private void EmitModuleVersionIdStore(BoundModuleVersionId node)
{
_builder.EmitOpCode(ILOpCode.Stsfld);
EmitModuleVersionIdToken(node);
}
private void EmitModuleVersionIdToken(BoundModuleVersionId node)
{
_builder.EmitToken(_module.GetModuleVersionId(_module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
}
private void EmitModuleVersionIdStringLoad(BoundModuleVersionIdString node)
{
_builder.EmitOpCode(ILOpCode.Ldstr);
_builder.EmitModuleVersionIdStringToken();
}
private void EmitInstrumentationPayloadRootLoad(BoundInstrumentationPayloadRoot node)
{
_builder.EmitOpCode(ILOpCode.Ldsfld);
EmitInstrumentationPayloadRootToken(node);
}
private void EmitInstrumentationPayloadRootStore(BoundInstrumentationPayloadRoot node)
{
_builder.EmitOpCode(ILOpCode.Stsfld);
EmitInstrumentationPayloadRootToken(node);
}
private void EmitInstrumentationPayloadRootToken(BoundInstrumentationPayloadRoot node)
{
_builder.EmitToken(_module.GetInstrumentationPayloadRoot(node.AnalysisKind, _module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
}
private void EmitSourceDocumentIndex(BoundSourceDocumentIndex node)
{
Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
_builder.EmitOpCode(ILOpCode.Ldtoken);
_builder.EmitSourceDocumentIndexToken(node.Document);
}
private void EmitMethodInfoExpression(BoundMethodInfo node)
{
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Method, node.Syntax, null);
MethodSymbol getMethod = node.GetMethodFromHandle;
Debug.Assert((object)getMethod != null);
if (getMethod.ParameterCount == 1)
{
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
}
else
{
Debug.Assert(getMethod.ParameterCount == 2);
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Method.ContainingType, node.Syntax);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
}
EmitSymbolToken(getMethod, node.Syntax, null);
if (!TypeSymbol.Equals(node.Type, getMethod.ReturnType, TypeCompareKind.ConsiderEverything2))
{
_builder.EmitOpCode(ILOpCode.Castclass);
EmitSymbolToken(node.Type, node.Syntax);
}
}
private void EmitFieldInfoExpression(BoundFieldInfo node)
{
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Field, node.Syntax);
MethodSymbol getField = node.GetFieldFromHandle;
Debug.Assert((object)getField != null);
if (getField.ParameterCount == 1)
{
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
}
else
{
Debug.Assert(getField.ParameterCount == 2);
_builder.EmitOpCode(ILOpCode.Ldtoken);
EmitSymbolToken(node.Field.ContainingType, node.Syntax);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
}
EmitSymbolToken(getField, node.Syntax, null);
if (!TypeSymbol.Equals(node.Type, getField.ReturnType, TypeCompareKind.ConsiderEverything2))
{
_builder.EmitOpCode(ILOpCode.Castclass);
EmitSymbolToken(node.Type, node.Syntax);
}
}
/// <summary>
/// Emit code for a conditional (aka ternary) operator.
/// </summary>
/// <remarks>
/// (b ? x : y) becomes
/// push b
/// if pop then goto CONSEQUENCE
/// push y
/// goto DONE
/// CONSEQUENCE:
/// push x
/// DONE:
/// </remarks>
private void EmitConditionalOperator(BoundConditionalOperator expr, bool used)
{
Debug.Assert(expr.ConstantValue == null, "Constant value should have been emitted directly");
object consequenceLabel = new object();
object doneLabel = new object();
EmitCondBranch(expr.Condition, ref consequenceLabel, sense: true);
EmitExpression(expr.Alternative, used);
//
// III.1.8.1.3 Merging stack states
// . . .
// Let T be the type from the slot on the newly computed state and S
// be the type from the corresponding slot on the previously stored state. The merged type, U, shall
// be computed as follows (recall that S := T is the compatibility function defined
// in §III.1.8.1.2.2):
// 1. if S := T then U=S
// 2. Otherwise, if T := S then U=T
// 3. Otherwise, if S and T are both object types, then let V be the closest common supertype of S and T then U=V.
// 4. Otherwise, the merge shall fail.
//
// When the target merge type is an interface that one or more classes implement, we emit static casts
// from any class to the target interface.
// You may think that it's possible to elide one of the static casts and have the CLR recognize
// that merging a class and interface should succeed if the class implements the interface. Unfortunately,
// it seems that either PEVerify or the runtime/JIT verifier will complain at you if you try to remove
// either of the casts.
//
var mergeTypeOfAlternative = StackMergeType(expr.Alternative);
if (used)
{
if (IsVarianceCast(expr.Type, mergeTypeOfAlternative))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfAlternative = expr.Type;
}
else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfAlternative, TypeCompareKind.ConsiderEverything2))
{
EmitStaticCast(expr.Type, expr.Syntax);
}
}
_builder.EmitBranch(ILOpCode.Br, doneLabel);
if (used)
{
// If we get to consequenceLabel, we should not have Alternative on stack, adjust for that.
_builder.AdjustStack(-1);
}
_builder.MarkLabel(consequenceLabel);
EmitExpression(expr.Consequence, used);
if (used)
{
var mergeTypeOfConsequence = StackMergeType(expr.Consequence);
if (IsVarianceCast(expr.Type, mergeTypeOfConsequence))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfConsequence = expr.Type;
}
else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfConsequence, TypeCompareKind.ConsiderEverything2))
{
EmitStaticCast(expr.Type, expr.Syntax);
}
}
_builder.MarkLabel(doneLabel);
}
/// <summary>
/// Emit code for a null-coalescing operator.
/// </summary>
/// <remarks>
/// x ?? y becomes
/// push x
/// dup x
/// if pop != null goto LEFT_NOT_NULL
/// pop
/// push y
/// LEFT_NOT_NULL:
/// </remarks>
private void EmitNullCoalescingOperator(BoundNullCoalescingOperator expr, bool used)
{
Debug.Assert(expr.LeftConversion.IsIdentity, "coalesce with nontrivial left conversions are lowered into conditional.");
Debug.Assert(expr.Type.IsReferenceType);
EmitExpression(expr.LeftOperand, used: true);
// See the notes about verification type merges in EmitConditionalOperator
var mergeTypeOfLeftValue = StackMergeType(expr.LeftOperand);
if (used)
{
if (IsVarianceCast(expr.Type, mergeTypeOfLeftValue))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfLeftValue = expr.Type;
}
else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfLeftValue, TypeCompareKind.ConsiderEverything2))
{
EmitStaticCast(expr.Type, expr.Syntax);
}
_builder.EmitOpCode(ILOpCode.Dup);
}
if (expr.Type.IsTypeParameter())
{
EmitBox(expr.Type, expr.LeftOperand.Syntax);
}
object ifLeftNotNullLabel = new object();
_builder.EmitBranch(ILOpCode.Brtrue, ifLeftNotNullLabel);
if (used)
{
_builder.EmitOpCode(ILOpCode.Pop);
}
EmitExpression(expr.RightOperand, used);
if (used)
{
var mergeTypeOfRightValue = StackMergeType(expr.RightOperand);
if (IsVarianceCast(expr.Type, mergeTypeOfRightValue))
{
EmitStaticCast(expr.Type, expr.Syntax);
mergeTypeOfRightValue = expr.Type;
}
}
_builder.MarkLabel(ifLeftNotNullLabel);
}
// Implicit casts are not emitted. As a result verifier may operate on a different
// types from the types of operands when performing stack merges in coalesce/conditional.
// Such differences are in general irrelevant since merging rules work the same way
// for base and derived types.
//
// Situation becomes more complicated with delegates, arrays and interfaces since they
// allow implicit casts from types that do not derive from them. In such cases
// we may need to introduce static casts in the code to prod the verifier to the
// right direction
//
// This helper returns actual type of array|interface|delegate expression ignoring implicit
// casts. This would be the effective stack merge type in the verifier.
//
// NOTE: In cases where stack merge type cannot be determined, we just return null.
// We still must assume that it can be an array, delegate or interface though.
private TypeSymbol StackMergeType(BoundExpression expr)
{
// these cases are not interesting. Merge type is the same or derived. No difference.
if (!(expr.Type.IsInterfaceType() || expr.Type.IsDelegateType()))
{
return expr.Type;
}
// Dig through casts. We only need to check for expressions that -
// 1) implicit casts
// 2) transparently return operands, so we need to dig deeper
// 3) stack values
switch (expr.Kind)
{
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
var conversionKind = conversion.ConversionKind;
Debug.Assert(conversionKind != ConversionKind.NullLiteral && conversionKind != ConversionKind.DefaultLiteral);
if (conversionKind.IsImplicitConversion() &&
conversionKind != ConversionKind.MethodGroup &&
conversionKind != ConversionKind.NullLiteral &&
conversionKind != ConversionKind.DefaultLiteral)
{
return StackMergeType(conversion.Operand);
}
break;
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
return StackMergeType(assignment.Right);
case BoundKind.Sequence:
var sequence = (BoundSequence)expr;
return StackMergeType(sequence.Value);
case BoundKind.Local:
var local = (BoundLocal)expr;
if (this.IsStackLocal(local.LocalSymbol))
{
// stack value, we cannot be sure what it is
return null;
}
break;
case BoundKind.Dup:
// stack value, we cannot be sure what it is
return null;
}
return expr.Type;
}
// Although III.1.8.1.3 seems to imply that verifier understands variance casts.
// It appears that verifier/JIT gets easily confused.
// So to not rely on whether that should work or not we will flag potentially
// "complicated" casts and make them static casts to ensure we are all on
// the same page with what type should be tracked.
private static bool IsVarianceCast(TypeSymbol to, TypeSymbol from)
{
if (TypeSymbol.Equals(to, from, TypeCompareKind.ConsiderEverything2))
{
return false;
}
if ((object)from == null)
{
// from unknown type - this could be a variance conversion.
return true;
}
// while technically variance casts, array conversions do not seem to be a problem
// unless the element types are converted via variance.
if (to.IsArray())
{
return IsVarianceCast(((ArrayTypeSymbol)to).ElementType, ((ArrayTypeSymbol)from).ElementType);
}
return (to.IsDelegateType() && !TypeSymbol.Equals(to, from, TypeCompareKind.ConsiderEverything2)) ||
(to.IsInterfaceType() && from.IsInterfaceType() && !from.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey((NamedTypeSymbol)to));
}
private void EmitStaticCast(TypeSymbol to, SyntaxNode syntax)
{
Debug.Assert(to.IsVerifierReference());
// From ILGENREC::GenQMark
// See VSWhidbey Bugs #49619 and 108643. If the destination type is an interface we need
// to force a static cast to be generated for any cast result expressions. The static cast
// should be done before the unifying jump so the code is verifiable and to allow the JIT to
// optimize it away. NOTE: Since there is no staticcast instruction, we implement static cast
// with a stloc / ldloc to a temporary.
// Bug: VSWhidbey/49619
// Bug: VSWhidbey/108643
// Bug: Devdiv/42645
var temp = AllocateTemp(to, syntax);
_builder.EmitLocalStore(temp);
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
}
private void EmitBox(TypeSymbol type, SyntaxNode syntaxNode)
{
Debug.Assert(!type.IsRefLikeType);
_builder.EmitOpCode(ILOpCode.Box);
EmitSymbolToken(type, syntaxNode);
}
private void EmitCalli(BoundFunctionPointerInvocation ptrInvocation, UseKind useKind)
{
EmitExpression(ptrInvocation.InvokedExpression, used: true);
LocalDefinition temp = null;
// The function pointer token must be the last thing on the stack before the
// calli invocation, but we need to preserve left-to-right semantics of the
// actual code. If there are arguments, therefore, we evaluate the code that
// produces the function pointer token, store it in a local, evaluate the
// arguments, then load that token again.
if (ptrInvocation.Arguments.Length > 0)
{
temp = AllocateTemp(ptrInvocation.InvokedExpression.Type, ptrInvocation.Syntax);
_builder.EmitLocalStore(temp);
}
FunctionPointerMethodSymbol method = ptrInvocation.FunctionPointer.Signature;
EmitArguments(ptrInvocation.Arguments, method.Parameters, ptrInvocation.ArgumentRefKindsOpt);
var stackBehavior = GetCallStackBehavior(ptrInvocation.FunctionPointer.Signature, ptrInvocation.Arguments);
if (temp is object)
{
_builder.EmitLocalLoad(temp);
FreeTemp(temp);
}
_builder.EmitOpCode(ILOpCode.Calli, stackBehavior);
EmitSignatureToken(ptrInvocation.FunctionPointer, ptrInvocation.Syntax);
EmitCallCleanup(ptrInvocation.Syntax, useKind, method);
}
private void EmitCallCleanup(SyntaxNode syntax, UseKind useKind, MethodSymbol method)
{
if (!method.ReturnsVoid)
{
EmitPopIfUnused(useKind != UseKind.Unused);
}
else if (_ilEmitStyle == ILEmitStyle.Debug)
{
// The only void methods with usable return values are constructors and the only
// time we see them here, the return should be unused.
Debug.Assert(useKind == UseKind.Unused, "Using the return value of a void method.");
Debug.Assert(_method.GenerateDebugInfo, "Implied by this.emitSequencePoints");
// DevDiv #15135. When a method like System.Diagnostics.Debugger.Break() is called, the
// debugger sees an event indicating that a user break (vs a breakpoint) has occurred.
// When this happens, it uses ICorDebugILFrame.GetIP(out uint, out CorDebugMappingResult)
// to determine the current instruction pointer. This method returns the instruction
// *after* the call. The source location is then given by the last sequence point before
// or on this instruction. As a result, if the instruction after the call has its own
// sequence point, then that sequence point will be used to determine the source location
// and the debugging experience will be disrupted. The easiest way to ensure that the next
// instruction does not have a sequence point is to insert a nop. Obviously, we only do this
// if debugging is enabled and optimization is disabled.
// From ILGENREC::genCall:
// We want to generate a NOP after CALL opcodes that end a statement so the debugger
// has better stepping behavior
// CONSIDER: In the native compiler, there's an additional restriction on when this nop is
// inserted. It is quite complicated, but it basically seems to say that, if we thought
// we could omit the temp-and-copy for a struct construction and it turned out that we
// couldn't (perhaps because the assigned local was captured by a lambda), and if we're
// not using the result of the constructor call (how can this even happen?), then we don't
// want to insert the nop. Since the consequence of not implementing this complicated logic
// is an extra nop in debug code, this is likely not a priority.
// CONSIDER: The native compiler also checks !(tree->flags & EXF_NODEBUGINFO). We don't have
// this mutable bit on our bound nodes, so we can't exactly match the behavior. We might be
// able to approximate the native behavior by inspecting call.WasCompilerGenerated, but it is
// not in a reliable state after lowering.
_builder.EmitOpCode(ILOpCode.Nop);
}
if (useKind == UseKind.UsedAsValue && method.RefKind != RefKind.None)
{
EmitLoadIndirect(method.ReturnType, syntax);
}
else if (useKind == UseKind.UsedAsAddress)
{
Debug.Assert(method.RefKind != RefKind.None);
}
}
private void EmitLoadFunction(BoundFunctionPointerLoad load, bool used)
{
Debug.Assert(load.Type is { TypeKind: TypeKind.FunctionPointer });
if (used)
{
if (load.TargetMethod.IsAbstract && load.TargetMethod.IsStatic)
{
if (load.ConstrainedToTypeOpt is not { TypeKind: TypeKind.TypeParameter })
{
throw ExceptionUtilities.Unreachable;
}
_builder.EmitOpCode(ILOpCode.Constrained);
EmitSymbolToken(load.ConstrainedToTypeOpt, load.Syntax);
}
_builder.EmitOpCode(ILOpCode.Ldftn);
EmitSymbolToken(load.TargetMethod, load.Syntax, optArgList: null);
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Analyzers/ValidateFormatString/CSharpValidateFormatStringDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.ValidateFormatString;
namespace Microsoft.CodeAnalysis.CSharp.ValidateFormatString
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpValidateFormatStringDiagnosticAnalyzer :
AbstractValidateFormatStringDiagnosticAnalyzer<SyntaxKind>
{
protected override ISyntaxFacts GetSyntaxFacts()
=> CSharpSyntaxFacts.Instance;
protected override SyntaxNode? TryGetMatchingNamedArgument(
SeparatedSyntaxList<SyntaxNode> arguments,
string searchArgumentName)
{
foreach (var argument in arguments.Cast<ArgumentSyntax>())
{
if (argument.NameColon != null && argument.NameColon.Name.Identifier.ValueText.Equals(searchArgumentName))
{
return argument;
}
}
return null;
}
protected override SyntaxNode GetArgumentExpression(SyntaxNode syntaxNode)
=> ((ArgumentSyntax)syntaxNode).Expression;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.ValidateFormatString;
namespace Microsoft.CodeAnalysis.CSharp.ValidateFormatString
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpValidateFormatStringDiagnosticAnalyzer :
AbstractValidateFormatStringDiagnosticAnalyzer<SyntaxKind>
{
protected override ISyntaxFacts GetSyntaxFacts()
=> CSharpSyntaxFacts.Instance;
protected override SyntaxNode? TryGetMatchingNamedArgument(
SeparatedSyntaxList<SyntaxNode> arguments,
string searchArgumentName)
{
foreach (var argument in arguments.Cast<ArgumentSyntax>())
{
if (argument.NameColon != null && argument.NameColon.Name.Identifier.ValueText.Equals(searchArgumentName))
{
return argument;
}
}
return null;
}
protected override SyntaxNode GetArgumentExpression(SyntaxNode syntaxNode)
=> ((ArgumentSyntax)syntaxNode).Expression;
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/IAnalyzerNodeSetup.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.VisualStudio.LanguageServices
{
/// <summary>
/// An interface to be implemented in the SolutionExplorerShim project to register the stuff needed there.
/// </summary>
internal interface IAnalyzerNodeSetup
{
void Initialize(IServiceProvider serviceProvider);
void Unregister();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.VisualStudio.LanguageServices
{
/// <summary>
/// An interface to be implemented in the SolutionExplorerShim project to register the stuff needed there.
/// </summary>
internal interface IAnalyzerNodeSetup
{
void Initialize(IServiceProvider serviceProvider);
void Unregister();
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/MakeClassAbstract/AbstractMakeTypeAbstractCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeTypeAbstract
{
internal abstract class AbstractMakeTypeAbstractCodeFixProvider<TTypeDeclarationSyntax> : SyntaxEditorBasedCodeFixProvider
where TTypeDeclarationSyntax : SyntaxNode
{
protected abstract bool IsValidRefactoringContext(SyntaxNode? node, [NotNullWhen(true)] out TTypeDeclarationSyntax? typeDeclaration);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
if (IsValidRefactoringContext(context.Diagnostics[0].Location?.FindNode(context.CancellationToken), out _))
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
}
return Task.CompletedTask;
}
protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
for (var i = 0; i < diagnostics.Length; i++)
{
if (IsValidRefactoringContext(diagnostics[i].Location?.FindNode(cancellationToken), out var typeDeclaration))
{
editor.ReplaceNode(typeDeclaration,
(currentTypeDeclaration, generator) => generator.WithModifiers(currentTypeDeclaration, generator.GetModifiers(currentTypeDeclaration).WithIsAbstract(true)));
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Make_class_abstract, createChangedDocument, FeaturesResources.Make_class_abstract)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeTypeAbstract
{
internal abstract class AbstractMakeTypeAbstractCodeFixProvider<TTypeDeclarationSyntax> : SyntaxEditorBasedCodeFixProvider
where TTypeDeclarationSyntax : SyntaxNode
{
protected abstract bool IsValidRefactoringContext(SyntaxNode? node, [NotNullWhen(true)] out TTypeDeclarationSyntax? typeDeclaration);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
if (IsValidRefactoringContext(context.Diagnostics[0].Location?.FindNode(context.CancellationToken), out _))
{
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
}
return Task.CompletedTask;
}
protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor,
CancellationToken cancellationToken)
{
for (var i = 0; i < diagnostics.Length; i++)
{
if (IsValidRefactoringContext(diagnostics[i].Location?.FindNode(cancellationToken), out var typeDeclaration))
{
editor.ReplaceNode(typeDeclaration,
(currentTypeDeclaration, generator) => generator.WithModifiers(currentTypeDeclaration, generator.GetModifiers(currentTypeDeclaration).WithIsAbstract(true)));
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Make_class_abstract, createChangedDocument, FeaturesResources.Make_class_abstract)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Shared/Extensions/ITextBufferEditExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class ITextBufferEditExtensions
{
#pragma warning disable IDE0052 // Remove unread private members - Used for debugging.
private static Exception? s_lastException = null;
#pragma warning restore IDE0052 // Remove unread private members
/// <summary>
/// Logs exceptions thrown during <see cref="ITextBufferEdit.Apply"/> as we look for issues.
/// </summary>
/// <param name="edit"></param>
/// <returns></returns>
public static ITextSnapshot ApplyAndLogExceptions(this ITextBufferEdit edit)
{
try
{
return edit.Apply();
}
catch (Exception e) when (ErrorReporting.FatalError.ReportAndCatch(e))
{
s_lastException = e;
// Since we don't know what is causing this yet, I don't feel safe that catching
// will not cause some further downstream failure. So we'll continue to propagate.
throw;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class ITextBufferEditExtensions
{
#pragma warning disable IDE0052 // Remove unread private members - Used for debugging.
private static Exception? s_lastException = null;
#pragma warning restore IDE0052 // Remove unread private members
/// <summary>
/// Logs exceptions thrown during <see cref="ITextBufferEdit.Apply"/> as we look for issues.
/// </summary>
/// <param name="edit"></param>
/// <returns></returns>
public static ITextSnapshot ApplyAndLogExceptions(this ITextBufferEdit edit)
{
try
{
return edit.Apply();
}
catch (Exception e) when (ErrorReporting.FatalError.ReportAndCatch(e))
{
s_lastException = e;
// Since we don't know what is causing this yet, I don't feel safe that catching
// will not cause some further downstream failure. So we'll continue to propagate.
throw;
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/ID.CSharpCommands.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices
{
internal static partial class ID
{
/// <summary>
/// Commands using the old C# command set GUID.
/// </summary>
public static class CSharpCommands
{
public const int AutoTokenCompletionForward = 0x1800; // cmdidAutoTokenCompletionForward
public const int AutoTokenCompletionBackward = 0x1801; // cmdidAutoTokenCompletionBackward
public const int ContextMenuGenerateMethodStub = 0x1900; // cmdidContextMenuGenerateMethodStub
public const int ContextImplementInterfaceImplicit = 0x1901; // cmdidContextImplementInterfaceImplicit
public const int ContextImplementInterfaceExplicit = 0x1902; // cmdidContextImplementInterfaceExplicit
public const int ContextImplementAbstractClass = 0x1903; // cmdidContextImplementAbstractClass
public const int ContextOrganizeRemoveAndSort = 0x1913; // cmdidContextOrganizeRemoveAndSort
public const int OrganizeSortUsings = 0x1922; // cmdidCSharpOrganizeSortUsings
public const int OrganizeRemoveAndSort = 0x1923; // cmdidCSharpOrganizeRemoveAndSort
public const int SmartTagRename = 0x2000; // cmdidSmartTagRename
public const int SmartTagRenameWithPreview = 0x2001; // cmdidSmartTagRenameWithPreview
public const int SmartTagReorderParameters = 0x2002; // cmdidSmartTagReorderParameters
public const int SmartTagRemoveParameters = 0x2003; // cmdidSmartTagRemoveParameters
public const int SmartTagImplementImplicit = 0x3000; // cmdidSmartTagImplementImplicit
public const int SmartTagImplementExplicit = 0x3001; // cmdidSmartTagImplementExplicit
public const int SmartTagImplementAbstract = 0x3002; // cmdidSmartTagImplementAbstract
public const int AddUsingForUnboundItem0 = 0x4000; // cmdidCSharpAddUsingForUnboundItem0
public const int AddUsingForUnboundItem1 = 0x4001; // cmdidCSharpAddUsingForUnboundItem1
public const int AddUsingForUnboundItem2 = 0x4002; // cmdidCSharpAddUsingForUnboundItem2
public const int AddUsingForUnboundItem3 = 0x4003; // cmdidCSharpAddUsingForUnboundItem3
public const int AddUsingForUnboundItem4 = 0x4004; // cmdidCSharpAddUsingForUnboundItem4
public const int AddUsingForUnboundItemMin = AddUsingForUnboundItem0;
public const int AddUsingForUnboundItemMax = AddUsingForUnboundItem4;
public const int SmartTagAddUsingForUnboundItem0 = 0x4005; // cmdidSmartTagAddUsingForUnboundItem0
public const int SmartTagAddUsingForUnboundItem1 = 0x4006; // cmdidSmartTagAddUsingForUnboundItem1
public const int SmartTagAddUsingForUnboundItem2 = 0x4007; // cmdidSmartTagAddUsingForUnboundItem2
public const int SmartTagAddUsingForUnboundItem3 = 0x4008; // cmdidSmartTagAddUsingForUnboundItem3
public const int SmartTagAddUsingForUnboundItem4 = 0x4009; // cmdidSmartTagAddUsingForUnboundItem4
public const int SmartTagAddUsingForUnboundItemMin = SmartTagAddUsingForUnboundItem0;
public const int SmartTagAddUsingForUnboundItemMax = SmartTagAddUsingForUnboundItem4;
public const int FullyQualifyUnboundItem0 = 0x4010; // cmdidCSharpFullyQualifyUnboundItem0
public const int FullyQualifyUnboundItem1 = 0x4011; // cmdidCSharpFullyQualifyUnboundItem1
public const int FullyQualifyUnboundItem2 = 0x4012; // cmdidCSharpFullyQualifyUnboundItem2
public const int FullyQualifyUnboundItem3 = 0x4013; // cmdidCSharpFullyQualifyUnboundItem3
public const int FullyQualifyUnboundItem4 = 0x4014; // cmdidCSharpFullyQualifyUnboundItem4
public const int FullyQualifyUnboundItemMin = FullyQualifyUnboundItem0;
public const int FullyQualifyUnboundItemMax = FullyQualifyUnboundItem4;
public const int SmartTagFullyQualifyUnboundItem0 = 0x4015; // cmdidSmartTagFullyQualifyUnboundItem0
public const int SmartTagFullyQualifyUnboundItem1 = 0x4016; // cmdidSmartTagFullyQualifyUnboundItem1
public const int SmartTagFullyQualifyUnboundItem2 = 0x4017; // cmdidSmartTagFullyQualifyUnboundItem2
public const int SmartTagFullyQualifyUnboundItem3 = 0x4018; // cmdidSmartTagFullyQualifyUnboundItem3
public const int SmartTagFullyQualifyUnboundItem4 = 0x4019; // cmdidSmartTagFullyQualifyUnboundItem4
public const int SmartTagFullyQualifyUnboundItemMin = SmartTagFullyQualifyUnboundItem0;
public const int SmartTagFullyQualifyUnboundItemMax = SmartTagFullyQualifyUnboundItem4;
public const int PartialMatchForUnboundItem0 = 0x4020; // cmdidCSharpPartialMatchForUnboundItem0
public const int PartialMatchForUnboundItem1 = 0x4021; // cmdidCSharpPartialMatchForUnboundItem1
public const int PartialMatchForUnboundItem2 = 0x4022; // cmdidCSharpPartialMatchForUnboundItem2
public const int PartialMatchForUnboundItem3 = 0x4023; // cmdidCSharpPartialMatchForUnboundItem3
public const int PartialMatchForUnboundItem4 = 0x4024; // cmdidCSharpPartialMatchForUnboundItem4
public const int PartialMatchForUnboundItem5 = 0x4025; // cmdidCSharpPartialMatchForUnboundItem5
public const int PartialMatchForUnboundItem6 = 0x4026; // cmdidCSharpPartialMatchForUnboundItem6
public const int PartialMatchForUnboundItem7 = 0x4027; // cmdidCSharpPartialMatchForUnboundItem7
public const int PartialMatchForUnboundItemMin = PartialMatchForUnboundItem0;
public const int PartialMatchForUnboundItemMax = PartialMatchForUnboundItem7;
public const int SmartTagPartialMatchForUnboundItem0 = 0x4028; // cmdidSmartTagPartialMatchForUnboundItem0
public const int SmartTagPartialMatchForUnboundItem1 = 0x4029; // cmdidSmartTagPartialMatchForUnboundItem1
public const int SmartTagPartialMatchForUnboundItem2 = 0x402A; // cmdidSmartTagPartialMatchForUnboundItem2
public const int SmartTagPartialMatchForUnboundItem3 = 0x402B; // cmdidSmartTagPartialMatchForUnboundItem3
public const int SmartTagPartialMatchForUnboundItem4 = 0x402C; // cmdidSmartTagPartialMatchForUnboundItem4
public const int SmartTagPartialMatchForUnboundItem5 = 0x402D; // cmdidSmartTagPartialMatchForUnboundItem5
public const int SmartTagPartialMatchForUnboundItem6 = 0x402E; // cmdidSmartTagPartialMatchForUnboundItem6
public const int SmartTagPartialMatchForUnboundItem7 = 0x402F; // cmdidSmartTagPartialMatchForUnboundItem7
public const int SmartTagPartialMatchForUnboundItemMin = SmartTagPartialMatchForUnboundItem0;
public const int SmartTagPartialMatchForUnboundItemMax = SmartTagPartialMatchForUnboundItem7;
public const int SmartTagGenerateMethodStub = 0x5000; // cmdidSmartTagGenerateMethodStub
public const int MenuGenerateConstructor = 0x5010; // cmdidMenuGenerateConstructor
public const int MenuGenerateProperty = 0x5011; // cmdidMenuGenerateProperty
public const int MenuGenerateClass = 0x5012; // cmdidMenuGenerateClass
public const int MenuGenerateNewType = 0x5013; // cmdidMenuGenerateNewType
public const int MenuGenerateEnumMember = 0x5014; // cmdidMenuGenerateEnumMember
public const int MenuGenerateField = 0x5015; // cmdidMenuGenerateField
public const int ContextMenuGenerateConstructor = 0x5020; // cmdidContextMenuGenerateConstructor
public const int ContextMenuGenerateProperty = 0x5021; // cmdidContextMenuGenerateProperty
public const int ContextMenuGenerateClass = 0x5022; // cmdidContextMenuGenerateClass
public const int ContextMenuGenerateNewType = 0x5023; // cmdidContextMenuGenerateNewType
public const int ContextMenuGenerateEnumMember = 0x5024; // cmdidContextMenuGenerateEnumMember
public const int ContextMenuGenerateField = 0x5025; // cmdidContextMenuGenerateField
public const int SmartTagGenerateConstructor = 0x5030; // cmdidSmartTagGenerateConstructor
public const int SmartTagGenerateProperty = 0x5031; // cmdidSmartTagGenerateProperty
public const int SmartTagGenerateClass = 0x5032; // cmdidSmartTagGenerateClass
public const int SmartTagGenerateNewType = 0x5036; // cmdidSmartTagGenerateNewType
public const int SmartTagGenerateEnumMember = 0x5037; // cmdidSmartTagGenerateEnumMember
public const int SmartTagGenerateField = 0x5038; // cmdidSmartTagGenerateField
public const int FormatComment = 0x6000; // cmdidCSharpFormatComment
public const int ContextFormatComment = 0x6001; // cmdidContextFormatComment
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices
{
internal static partial class ID
{
/// <summary>
/// Commands using the old C# command set GUID.
/// </summary>
public static class CSharpCommands
{
public const int AutoTokenCompletionForward = 0x1800; // cmdidAutoTokenCompletionForward
public const int AutoTokenCompletionBackward = 0x1801; // cmdidAutoTokenCompletionBackward
public const int ContextMenuGenerateMethodStub = 0x1900; // cmdidContextMenuGenerateMethodStub
public const int ContextImplementInterfaceImplicit = 0x1901; // cmdidContextImplementInterfaceImplicit
public const int ContextImplementInterfaceExplicit = 0x1902; // cmdidContextImplementInterfaceExplicit
public const int ContextImplementAbstractClass = 0x1903; // cmdidContextImplementAbstractClass
public const int ContextOrganizeRemoveAndSort = 0x1913; // cmdidContextOrganizeRemoveAndSort
public const int OrganizeSortUsings = 0x1922; // cmdidCSharpOrganizeSortUsings
public const int OrganizeRemoveAndSort = 0x1923; // cmdidCSharpOrganizeRemoveAndSort
public const int SmartTagRename = 0x2000; // cmdidSmartTagRename
public const int SmartTagRenameWithPreview = 0x2001; // cmdidSmartTagRenameWithPreview
public const int SmartTagReorderParameters = 0x2002; // cmdidSmartTagReorderParameters
public const int SmartTagRemoveParameters = 0x2003; // cmdidSmartTagRemoveParameters
public const int SmartTagImplementImplicit = 0x3000; // cmdidSmartTagImplementImplicit
public const int SmartTagImplementExplicit = 0x3001; // cmdidSmartTagImplementExplicit
public const int SmartTagImplementAbstract = 0x3002; // cmdidSmartTagImplementAbstract
public const int AddUsingForUnboundItem0 = 0x4000; // cmdidCSharpAddUsingForUnboundItem0
public const int AddUsingForUnboundItem1 = 0x4001; // cmdidCSharpAddUsingForUnboundItem1
public const int AddUsingForUnboundItem2 = 0x4002; // cmdidCSharpAddUsingForUnboundItem2
public const int AddUsingForUnboundItem3 = 0x4003; // cmdidCSharpAddUsingForUnboundItem3
public const int AddUsingForUnboundItem4 = 0x4004; // cmdidCSharpAddUsingForUnboundItem4
public const int AddUsingForUnboundItemMin = AddUsingForUnboundItem0;
public const int AddUsingForUnboundItemMax = AddUsingForUnboundItem4;
public const int SmartTagAddUsingForUnboundItem0 = 0x4005; // cmdidSmartTagAddUsingForUnboundItem0
public const int SmartTagAddUsingForUnboundItem1 = 0x4006; // cmdidSmartTagAddUsingForUnboundItem1
public const int SmartTagAddUsingForUnboundItem2 = 0x4007; // cmdidSmartTagAddUsingForUnboundItem2
public const int SmartTagAddUsingForUnboundItem3 = 0x4008; // cmdidSmartTagAddUsingForUnboundItem3
public const int SmartTagAddUsingForUnboundItem4 = 0x4009; // cmdidSmartTagAddUsingForUnboundItem4
public const int SmartTagAddUsingForUnboundItemMin = SmartTagAddUsingForUnboundItem0;
public const int SmartTagAddUsingForUnboundItemMax = SmartTagAddUsingForUnboundItem4;
public const int FullyQualifyUnboundItem0 = 0x4010; // cmdidCSharpFullyQualifyUnboundItem0
public const int FullyQualifyUnboundItem1 = 0x4011; // cmdidCSharpFullyQualifyUnboundItem1
public const int FullyQualifyUnboundItem2 = 0x4012; // cmdidCSharpFullyQualifyUnboundItem2
public const int FullyQualifyUnboundItem3 = 0x4013; // cmdidCSharpFullyQualifyUnboundItem3
public const int FullyQualifyUnboundItem4 = 0x4014; // cmdidCSharpFullyQualifyUnboundItem4
public const int FullyQualifyUnboundItemMin = FullyQualifyUnboundItem0;
public const int FullyQualifyUnboundItemMax = FullyQualifyUnboundItem4;
public const int SmartTagFullyQualifyUnboundItem0 = 0x4015; // cmdidSmartTagFullyQualifyUnboundItem0
public const int SmartTagFullyQualifyUnboundItem1 = 0x4016; // cmdidSmartTagFullyQualifyUnboundItem1
public const int SmartTagFullyQualifyUnboundItem2 = 0x4017; // cmdidSmartTagFullyQualifyUnboundItem2
public const int SmartTagFullyQualifyUnboundItem3 = 0x4018; // cmdidSmartTagFullyQualifyUnboundItem3
public const int SmartTagFullyQualifyUnboundItem4 = 0x4019; // cmdidSmartTagFullyQualifyUnboundItem4
public const int SmartTagFullyQualifyUnboundItemMin = SmartTagFullyQualifyUnboundItem0;
public const int SmartTagFullyQualifyUnboundItemMax = SmartTagFullyQualifyUnboundItem4;
public const int PartialMatchForUnboundItem0 = 0x4020; // cmdidCSharpPartialMatchForUnboundItem0
public const int PartialMatchForUnboundItem1 = 0x4021; // cmdidCSharpPartialMatchForUnboundItem1
public const int PartialMatchForUnboundItem2 = 0x4022; // cmdidCSharpPartialMatchForUnboundItem2
public const int PartialMatchForUnboundItem3 = 0x4023; // cmdidCSharpPartialMatchForUnboundItem3
public const int PartialMatchForUnboundItem4 = 0x4024; // cmdidCSharpPartialMatchForUnboundItem4
public const int PartialMatchForUnboundItem5 = 0x4025; // cmdidCSharpPartialMatchForUnboundItem5
public const int PartialMatchForUnboundItem6 = 0x4026; // cmdidCSharpPartialMatchForUnboundItem6
public const int PartialMatchForUnboundItem7 = 0x4027; // cmdidCSharpPartialMatchForUnboundItem7
public const int PartialMatchForUnboundItemMin = PartialMatchForUnboundItem0;
public const int PartialMatchForUnboundItemMax = PartialMatchForUnboundItem7;
public const int SmartTagPartialMatchForUnboundItem0 = 0x4028; // cmdidSmartTagPartialMatchForUnboundItem0
public const int SmartTagPartialMatchForUnboundItem1 = 0x4029; // cmdidSmartTagPartialMatchForUnboundItem1
public const int SmartTagPartialMatchForUnboundItem2 = 0x402A; // cmdidSmartTagPartialMatchForUnboundItem2
public const int SmartTagPartialMatchForUnboundItem3 = 0x402B; // cmdidSmartTagPartialMatchForUnboundItem3
public const int SmartTagPartialMatchForUnboundItem4 = 0x402C; // cmdidSmartTagPartialMatchForUnboundItem4
public const int SmartTagPartialMatchForUnboundItem5 = 0x402D; // cmdidSmartTagPartialMatchForUnboundItem5
public const int SmartTagPartialMatchForUnboundItem6 = 0x402E; // cmdidSmartTagPartialMatchForUnboundItem6
public const int SmartTagPartialMatchForUnboundItem7 = 0x402F; // cmdidSmartTagPartialMatchForUnboundItem7
public const int SmartTagPartialMatchForUnboundItemMin = SmartTagPartialMatchForUnboundItem0;
public const int SmartTagPartialMatchForUnboundItemMax = SmartTagPartialMatchForUnboundItem7;
public const int SmartTagGenerateMethodStub = 0x5000; // cmdidSmartTagGenerateMethodStub
public const int MenuGenerateConstructor = 0x5010; // cmdidMenuGenerateConstructor
public const int MenuGenerateProperty = 0x5011; // cmdidMenuGenerateProperty
public const int MenuGenerateClass = 0x5012; // cmdidMenuGenerateClass
public const int MenuGenerateNewType = 0x5013; // cmdidMenuGenerateNewType
public const int MenuGenerateEnumMember = 0x5014; // cmdidMenuGenerateEnumMember
public const int MenuGenerateField = 0x5015; // cmdidMenuGenerateField
public const int ContextMenuGenerateConstructor = 0x5020; // cmdidContextMenuGenerateConstructor
public const int ContextMenuGenerateProperty = 0x5021; // cmdidContextMenuGenerateProperty
public const int ContextMenuGenerateClass = 0x5022; // cmdidContextMenuGenerateClass
public const int ContextMenuGenerateNewType = 0x5023; // cmdidContextMenuGenerateNewType
public const int ContextMenuGenerateEnumMember = 0x5024; // cmdidContextMenuGenerateEnumMember
public const int ContextMenuGenerateField = 0x5025; // cmdidContextMenuGenerateField
public const int SmartTagGenerateConstructor = 0x5030; // cmdidSmartTagGenerateConstructor
public const int SmartTagGenerateProperty = 0x5031; // cmdidSmartTagGenerateProperty
public const int SmartTagGenerateClass = 0x5032; // cmdidSmartTagGenerateClass
public const int SmartTagGenerateNewType = 0x5036; // cmdidSmartTagGenerateNewType
public const int SmartTagGenerateEnumMember = 0x5037; // cmdidSmartTagGenerateEnumMember
public const int SmartTagGenerateField = 0x5038; // cmdidSmartTagGenerateField
public const int FormatComment = 0x6000; // cmdidCSharpFormatComment
public const int ContextFormatComment = 0x6001; // cmdidContextFormatComment
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/UnusedReferences/RemoveUnusedReferencesCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Design;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.UnusedReferences;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog;
using Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.ProjectAssets;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences
{
[Export(typeof(RemoveUnusedReferencesCommandHandler)), Shared]
internal sealed class RemoveUnusedReferencesCommandHandler
{
private const string ProjectAssetsFilePropertyName = "ProjectAssetsFile";
private readonly Lazy<IReferenceCleanupService> _lazyReferenceCleanupService;
private readonly RemoveUnusedReferencesDialogProvider _unusedReferenceDialogProvider;
private readonly VisualStudioWorkspace _workspace;
private readonly IUIThreadOperationExecutor _threadOperationExecutor;
private IServiceProvider? _serviceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoveUnusedReferencesCommandHandler(
RemoveUnusedReferencesDialogProvider unusedReferenceDialogProvider,
IUIThreadOperationExecutor threadOperationExecutor,
VisualStudioWorkspace workspace)
{
_unusedReferenceDialogProvider = unusedReferenceDialogProvider;
_threadOperationExecutor = threadOperationExecutor;
_workspace = workspace;
_lazyReferenceCleanupService = new(() => workspace.Services.GetRequiredService<IReferenceCleanupService>());
}
public void Initialize(IServiceProvider serviceProvider)
{
Contract.ThrowIfNull(serviceProvider);
_serviceProvider = serviceProvider;
// Hook up the "Remove Unused References" menu command for CPS based managed projects.
var menuCommandService = (IMenuCommandService)_serviceProvider.GetService(typeof(IMenuCommandService));
if (menuCommandService != null)
{
VisualStudioCommandHandlerHelpers.AddCommand(menuCommandService, ID.RoslynCommands.RemoveUnusedReferences, Guids.RoslynGroupId, OnRemoveUnusedReferencesForSelectedProject, OnRemoveUnusedReferencesForSelectedProjectStatus);
}
}
private void OnRemoveUnusedReferencesForSelectedProjectStatus(object sender, EventArgs e)
{
var command = (OleMenuCommand)sender;
var experimentationService = _workspace.Services.GetRequiredService<IExperimentationService>();
// If the option hasn't been expicitly set then fallback to whether this is enabled as part of an experiment.
var isOptionEnabled = _workspace.Options.GetOption(FeatureOnOffOptions.OfferRemoveUnusedReferences)
?? experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences);
var isDotNetCpsProject = VisualStudioCommandHandlerHelpers.TryGetSelectedProjectHierarchy(_serviceProvider, out var hierarchy) &&
hierarchy.IsCapabilityMatch("CPS") &&
hierarchy.IsCapabilityMatch(".NET");
// Only show the "Remove Unused Reference" menu commands for CPS based managed projects.
var visible = isOptionEnabled && isDotNetCpsProject;
var enabled = false;
if (visible)
{
enabled = !VisualStudioCommandHandlerHelpers.IsBuildActive();
}
if (command.Visible != visible)
{
command.Visible = visible;
}
if (command.Enabled != enabled)
{
command.Enabled = enabled;
}
}
private void OnRemoveUnusedReferencesForSelectedProject(object sender, EventArgs args)
{
if (VisualStudioCommandHandlerHelpers.TryGetSelectedProjectHierarchy(_serviceProvider, out var hierarchy))
{
Solution? solution = null;
string? projectFilePath = null;
ImmutableArray<ReferenceUpdate> referenceUpdates = default;
var status = _threadOperationExecutor.Execute(ServicesVSResources.Remove_Unused_References, ServicesVSResources.Analyzing_project_references, allowCancellation: true, showProgress: true, (operationContext) =>
{
(solution, projectFilePath, referenceUpdates) = GetUnusedReferencesForProjectHierarchy(hierarchy, operationContext.UserCancellationToken);
});
if (status == UIThreadOperationStatus.Canceled)
{
return;
}
if (solution is null ||
projectFilePath is not string { Length: > 0 } ||
referenceUpdates.IsEmpty)
{
MessageDialog.Show(ServicesVSResources.Remove_Unused_References, ServicesVSResources.No_unused_references_were_found, MessageDialogCommandSet.Ok);
return;
}
var dialog = _unusedReferenceDialogProvider.CreateDialog();
if (dialog.ShowModal(solution, projectFilePath, referenceUpdates) == false)
{
return;
}
// If we are removing, then that is a change or if we are newly marking a reference as TreatAsUsed,
// then that is a change.
var referenceChanges = referenceUpdates
.Where(update => update.Action != UpdateAction.TreatAsUsed || !update.ReferenceInfo.TreatAsUsed)
.ToImmutableArray();
// If there are no changes, then we can return
if (referenceChanges.IsEmpty)
{
return;
}
// Since undo/redo is not supported, get confirmation that we should apply these changes.
var result = MessageDialog.Show(ServicesVSResources.Remove_Unused_References, ServicesVSResources.This_action_cannot_be_undone_Do_you_wish_to_continue, MessageDialogCommandSet.YesNo);
if (result == MessageDialogCommand.No)
{
return;
}
_threadOperationExecutor.Execute(ServicesVSResources.Remove_Unused_References, ServicesVSResources.Updating_project_references, allowCancellation: false, showProgress: true, (operationContext) =>
{
ApplyUnusedReferenceUpdates(solution, projectFilePath, referenceChanges, CancellationToken.None);
});
}
return;
}
private (Solution?, string?, ImmutableArray<ReferenceUpdate>) GetUnusedReferencesForProjectHierarchy(
IVsHierarchy projectHierarchy,
CancellationToken cancellationToken)
{
if (!TryGetPropertyValue(projectHierarchy, ProjectAssetsFilePropertyName, out var projectAssetsFile))
{
return (null, null, ImmutableArray<ReferenceUpdate>.Empty);
}
var projectFilePath = projectHierarchy.TryGetProjectFilePath();
if (string.IsNullOrEmpty(projectFilePath))
{
return (null, null, ImmutableArray<ReferenceUpdate>.Empty);
}
var solution = _workspace.CurrentSolution;
var unusedReferences = GetUnusedReferencesForProject(solution, projectFilePath!, projectAssetsFile, cancellationToken);
return (solution, projectFilePath, unusedReferences);
}
private ImmutableArray<ReferenceUpdate> GetUnusedReferencesForProject(Solution solution, string projectFilePath, string projectAssetsFile, CancellationToken cancellationToken)
{
var unusedReferences = ThreadHelper.JoinableTaskFactory.Run(async () =>
{
var projectReferences = await _lazyReferenceCleanupService.Value.GetProjectReferencesAsync(projectFilePath, cancellationToken).ConfigureAwait(true);
var references = ProjectAssetsReader.ReadReferences(projectReferences, projectAssetsFile);
return await UnusedReferencesRemover.GetUnusedReferencesAsync(solution, projectFilePath, references, cancellationToken).ConfigureAwait(true);
});
var referenceUpdates = unusedReferences
.Select(reference => new ReferenceUpdate(reference.TreatAsUsed ? UpdateAction.TreatAsUsed : UpdateAction.Remove, reference))
.ToImmutableArray();
return referenceUpdates;
}
private void ApplyUnusedReferenceUpdates(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates, CancellationToken cancellationToken)
{
ThreadHelper.JoinableTaskFactory.Run(
() => UnusedReferencesRemover.UpdateReferencesAsync(solution, projectFilePath, referenceUpdates, cancellationToken));
}
private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, [NotNullWhen(returnValue: true)] out string? propertyValue)
{
if (hierarchy is not IVsBuildPropertyStorage storage)
{
propertyValue = null;
return false;
}
return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Design;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.UnusedReferences;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog;
using Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.ProjectAssets;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences
{
[Export(typeof(RemoveUnusedReferencesCommandHandler)), Shared]
internal sealed class RemoveUnusedReferencesCommandHandler
{
private const string ProjectAssetsFilePropertyName = "ProjectAssetsFile";
private readonly Lazy<IReferenceCleanupService> _lazyReferenceCleanupService;
private readonly RemoveUnusedReferencesDialogProvider _unusedReferenceDialogProvider;
private readonly VisualStudioWorkspace _workspace;
private readonly IUIThreadOperationExecutor _threadOperationExecutor;
private IServiceProvider? _serviceProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoveUnusedReferencesCommandHandler(
RemoveUnusedReferencesDialogProvider unusedReferenceDialogProvider,
IUIThreadOperationExecutor threadOperationExecutor,
VisualStudioWorkspace workspace)
{
_unusedReferenceDialogProvider = unusedReferenceDialogProvider;
_threadOperationExecutor = threadOperationExecutor;
_workspace = workspace;
_lazyReferenceCleanupService = new(() => workspace.Services.GetRequiredService<IReferenceCleanupService>());
}
public void Initialize(IServiceProvider serviceProvider)
{
Contract.ThrowIfNull(serviceProvider);
_serviceProvider = serviceProvider;
// Hook up the "Remove Unused References" menu command for CPS based managed projects.
var menuCommandService = (IMenuCommandService)_serviceProvider.GetService(typeof(IMenuCommandService));
if (menuCommandService != null)
{
VisualStudioCommandHandlerHelpers.AddCommand(menuCommandService, ID.RoslynCommands.RemoveUnusedReferences, Guids.RoslynGroupId, OnRemoveUnusedReferencesForSelectedProject, OnRemoveUnusedReferencesForSelectedProjectStatus);
}
}
private void OnRemoveUnusedReferencesForSelectedProjectStatus(object sender, EventArgs e)
{
var command = (OleMenuCommand)sender;
var experimentationService = _workspace.Services.GetRequiredService<IExperimentationService>();
// If the option hasn't been expicitly set then fallback to whether this is enabled as part of an experiment.
var isOptionEnabled = _workspace.Options.GetOption(FeatureOnOffOptions.OfferRemoveUnusedReferences)
?? experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences);
var isDotNetCpsProject = VisualStudioCommandHandlerHelpers.TryGetSelectedProjectHierarchy(_serviceProvider, out var hierarchy) &&
hierarchy.IsCapabilityMatch("CPS") &&
hierarchy.IsCapabilityMatch(".NET");
// Only show the "Remove Unused Reference" menu commands for CPS based managed projects.
var visible = isOptionEnabled && isDotNetCpsProject;
var enabled = false;
if (visible)
{
enabled = !VisualStudioCommandHandlerHelpers.IsBuildActive();
}
if (command.Visible != visible)
{
command.Visible = visible;
}
if (command.Enabled != enabled)
{
command.Enabled = enabled;
}
}
private void OnRemoveUnusedReferencesForSelectedProject(object sender, EventArgs args)
{
if (VisualStudioCommandHandlerHelpers.TryGetSelectedProjectHierarchy(_serviceProvider, out var hierarchy))
{
Solution? solution = null;
string? projectFilePath = null;
ImmutableArray<ReferenceUpdate> referenceUpdates = default;
var status = _threadOperationExecutor.Execute(ServicesVSResources.Remove_Unused_References, ServicesVSResources.Analyzing_project_references, allowCancellation: true, showProgress: true, (operationContext) =>
{
(solution, projectFilePath, referenceUpdates) = GetUnusedReferencesForProjectHierarchy(hierarchy, operationContext.UserCancellationToken);
});
if (status == UIThreadOperationStatus.Canceled)
{
return;
}
if (solution is null ||
projectFilePath is not string { Length: > 0 } ||
referenceUpdates.IsEmpty)
{
MessageDialog.Show(ServicesVSResources.Remove_Unused_References, ServicesVSResources.No_unused_references_were_found, MessageDialogCommandSet.Ok);
return;
}
var dialog = _unusedReferenceDialogProvider.CreateDialog();
if (dialog.ShowModal(solution, projectFilePath, referenceUpdates) == false)
{
return;
}
// If we are removing, then that is a change or if we are newly marking a reference as TreatAsUsed,
// then that is a change.
var referenceChanges = referenceUpdates
.Where(update => update.Action != UpdateAction.TreatAsUsed || !update.ReferenceInfo.TreatAsUsed)
.ToImmutableArray();
// If there are no changes, then we can return
if (referenceChanges.IsEmpty)
{
return;
}
// Since undo/redo is not supported, get confirmation that we should apply these changes.
var result = MessageDialog.Show(ServicesVSResources.Remove_Unused_References, ServicesVSResources.This_action_cannot_be_undone_Do_you_wish_to_continue, MessageDialogCommandSet.YesNo);
if (result == MessageDialogCommand.No)
{
return;
}
_threadOperationExecutor.Execute(ServicesVSResources.Remove_Unused_References, ServicesVSResources.Updating_project_references, allowCancellation: false, showProgress: true, (operationContext) =>
{
ApplyUnusedReferenceUpdates(solution, projectFilePath, referenceChanges, CancellationToken.None);
});
}
return;
}
private (Solution?, string?, ImmutableArray<ReferenceUpdate>) GetUnusedReferencesForProjectHierarchy(
IVsHierarchy projectHierarchy,
CancellationToken cancellationToken)
{
if (!TryGetPropertyValue(projectHierarchy, ProjectAssetsFilePropertyName, out var projectAssetsFile))
{
return (null, null, ImmutableArray<ReferenceUpdate>.Empty);
}
var projectFilePath = projectHierarchy.TryGetProjectFilePath();
if (string.IsNullOrEmpty(projectFilePath))
{
return (null, null, ImmutableArray<ReferenceUpdate>.Empty);
}
var solution = _workspace.CurrentSolution;
var unusedReferences = GetUnusedReferencesForProject(solution, projectFilePath!, projectAssetsFile, cancellationToken);
return (solution, projectFilePath, unusedReferences);
}
private ImmutableArray<ReferenceUpdate> GetUnusedReferencesForProject(Solution solution, string projectFilePath, string projectAssetsFile, CancellationToken cancellationToken)
{
var unusedReferences = ThreadHelper.JoinableTaskFactory.Run(async () =>
{
var projectReferences = await _lazyReferenceCleanupService.Value.GetProjectReferencesAsync(projectFilePath, cancellationToken).ConfigureAwait(true);
var references = ProjectAssetsReader.ReadReferences(projectReferences, projectAssetsFile);
return await UnusedReferencesRemover.GetUnusedReferencesAsync(solution, projectFilePath, references, cancellationToken).ConfigureAwait(true);
});
var referenceUpdates = unusedReferences
.Select(reference => new ReferenceUpdate(reference.TreatAsUsed ? UpdateAction.TreatAsUsed : UpdateAction.Remove, reference))
.ToImmutableArray();
return referenceUpdates;
}
private void ApplyUnusedReferenceUpdates(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates, CancellationToken cancellationToken)
{
ThreadHelper.JoinableTaskFactory.Run(
() => UnusedReferencesRemover.UpdateReferencesAsync(solution, projectFilePath, referenceUpdates, cancellationToken));
}
private static bool TryGetPropertyValue(IVsHierarchy hierarchy, string propertyName, [NotNullWhen(returnValue: true)] out string? propertyValue)
{
if (hierarchy is not IVsBuildPropertyStorage storage)
{
propertyValue = null;
return false;
}
return ErrorHandler.Succeeded(storage.GetPropertyValue(propertyName, null, (uint)_PersistStorageType.PST_PROJECT_FILE, out propertyValue));
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SemanticModelExtensions
{
/// <summary>
/// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token.
/// </summary>
/// <param name="semanticModel">The SemanticModel object to get semantic information
/// from.</param>
/// <param name="token">The token to get semantic information from. This must be part of the
/// syntax tree associated with the binding.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
=> semanticModel.GetSymbolInfo(token.Parent!, cancellationToken);
public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken)
{
return semanticModel.GetDeclaredSymbol(declaration, cancellationToken)
?? throw new InvalidOperationException();
}
public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol(position, cancellationToken)
?? throw new InvalidOperationException();
}
public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
where TSymbol : class, ISymbol
{
for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken);
symbol != null;
symbol = symbol.ContainingSymbol)
{
if (symbol is TSymbol tSymbol)
{
return tSymbol;
}
}
return null;
}
public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ??
(ISymbol)semanticModel.Compilation.Assembly;
}
public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken);
public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken);
public static IEnumerable<ISymbol> GetExistingSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
// Ignore an anonymous type property or tuple field. It's ok if they have a name that
// matches the name of the local we're introducing.
return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto)
.Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField());
}
public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel)
{
if (!semanticModel.IsSpeculativeSemanticModel)
{
return semanticModel;
}
Contract.ThrowIfNull(semanticModel.ParentModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null);
return semanticModel.ParentModel;
}
public static HashSet<ISymbol> GetAllDeclaredSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null)
{
var symbols = new HashSet<ISymbol>();
if (container != null)
{
GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter);
}
return symbols;
}
private static void GetAllDeclaredSymbols(
SemanticModel semanticModel, SyntaxNode node,
HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (symbol != null)
{
symbols.Add(symbol);
}
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
{
var childNode = child.AsNode()!;
if (ShouldDescendInto(childNode, descendInto))
{
GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto);
}
}
}
static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter)
=> filter != null ? filter(node) : true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SemanticModelExtensions
{
/// <summary>
/// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token.
/// </summary>
/// <param name="semanticModel">The SemanticModel object to get semantic information
/// from.</param>
/// <param name="token">The token to get semantic information from. This must be part of the
/// syntax tree associated with the binding.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
=> semanticModel.GetSymbolInfo(token.Parent!, cancellationToken);
public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken)
{
return semanticModel.GetDeclaredSymbol(declaration, cancellationToken)
?? throw new InvalidOperationException();
}
public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol(position, cancellationToken)
?? throw new InvalidOperationException();
}
public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
where TSymbol : class, ISymbol
{
for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken);
symbol != null;
symbol = symbol.ContainingSymbol)
{
if (symbol is TSymbol tSymbol)
{
return tSymbol;
}
}
return null;
}
public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ??
(ISymbol)semanticModel.Compilation.Assembly;
}
public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken);
public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken);
public static IEnumerable<ISymbol> GetExistingSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
// Ignore an anonymous type property or tuple field. It's ok if they have a name that
// matches the name of the local we're introducing.
return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto)
.Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField());
}
public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel)
{
if (!semanticModel.IsSpeculativeSemanticModel)
{
return semanticModel;
}
Contract.ThrowIfNull(semanticModel.ParentModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null);
return semanticModel.ParentModel;
}
public static HashSet<ISymbol> GetAllDeclaredSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null)
{
var symbols = new HashSet<ISymbol>();
if (container != null)
{
GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter);
}
return symbols;
}
private static void GetAllDeclaredSymbols(
SemanticModel semanticModel, SyntaxNode node,
HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (symbol != null)
{
symbols.Add(symbol);
}
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
{
var childNode = child.AsNode()!;
if (ShouldDescendInto(childNode, descendInto))
{
GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto);
}
}
}
static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter)
=> filter != null ? filter(node) : true;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Symbols/IFieldSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a field in a class, struct or enum.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IFieldSymbol : ISymbol
{
/// <summary>
/// If this field serves as a backing variable for an automatically generated
/// property or a field-like event, returns that
/// property/event. Otherwise returns null.
/// Note, the set of possible associated symbols might be expanded in the future to
/// reflect changes in the languages.
/// </summary>
ISymbol? AssociatedSymbol { get; }
/// <summary>
/// Returns true if this field was declared as "const" (i.e. is a constant declaration).
/// Also returns true for an enum member.
/// </summary>
bool IsConst { get; }
/// <summary>
/// Returns true if this field was declared as "readonly".
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Returns true if this field was declared as "volatile".
/// </summary>
bool IsVolatile { get; }
/// <summary>
/// Returns true if this field was declared as "fixed".
/// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which
/// the pointed-to type will be the declared element type of the fixed-size buffer.
/// </summary>
bool IsFixedSizeBuffer { get; }
/// <summary>
/// Gets the type of this field.
/// </summary>
ITypeSymbol Type { get; }
/// <summary>
/// Gets the top-level nullability of this field.
/// </summary>
NullableAnnotation NullableAnnotation { get; }
/// <summary>
/// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous.
/// True otherwise.
/// </summary>
[MemberNotNullWhen(true, nameof(ConstantValue))]
bool HasConstantValue { get; }
/// <summary>
/// Gets the constant value of this field
/// </summary>
object? ConstantValue { get; }
/// <summary>
/// Returns custom modifiers associated with the field, or an empty array if there are none.
/// </summary>
ImmutableArray<CustomModifier> CustomModifiers { get; }
/// <summary>
/// Get the original definition of this symbol. If this symbol is derived from another
/// symbol by (say) type substitution, this gets the original symbol, as it was defined in
/// source or metadata.
/// </summary>
new IFieldSymbol OriginalDefinition { get; }
/// <summary>
/// If this field represents a tuple element, returns a corresponding default element field.
/// Otherwise returns null.
/// </summary>
/// <remarks>
/// A tuple type will always have default elements such as Item1, Item2, Item3...
/// This API allows matching a field that represents a named element, such as "Alice"
/// to the corresponding default element field such as "Item1"
/// </remarks>
IFieldSymbol? CorrespondingTupleField { get; }
/// <summary>
/// Returns true if this field represents a tuple element which was given an explicit name.
/// </summary>
bool IsExplicitlyNamedTupleElement { 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 System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a field in a class, struct or enum.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IFieldSymbol : ISymbol
{
/// <summary>
/// If this field serves as a backing variable for an automatically generated
/// property or a field-like event, returns that
/// property/event. Otherwise returns null.
/// Note, the set of possible associated symbols might be expanded in the future to
/// reflect changes in the languages.
/// </summary>
ISymbol? AssociatedSymbol { get; }
/// <summary>
/// Returns true if this field was declared as "const" (i.e. is a constant declaration).
/// Also returns true for an enum member.
/// </summary>
bool IsConst { get; }
/// <summary>
/// Returns true if this field was declared as "readonly".
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Returns true if this field was declared as "volatile".
/// </summary>
bool IsVolatile { get; }
/// <summary>
/// Returns true if this field was declared as "fixed".
/// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which
/// the pointed-to type will be the declared element type of the fixed-size buffer.
/// </summary>
bool IsFixedSizeBuffer { get; }
/// <summary>
/// Gets the type of this field.
/// </summary>
ITypeSymbol Type { get; }
/// <summary>
/// Gets the top-level nullability of this field.
/// </summary>
NullableAnnotation NullableAnnotation { get; }
/// <summary>
/// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous.
/// True otherwise.
/// </summary>
[MemberNotNullWhen(true, nameof(ConstantValue))]
bool HasConstantValue { get; }
/// <summary>
/// Gets the constant value of this field
/// </summary>
object? ConstantValue { get; }
/// <summary>
/// Returns custom modifiers associated with the field, or an empty array if there are none.
/// </summary>
ImmutableArray<CustomModifier> CustomModifiers { get; }
/// <summary>
/// Get the original definition of this symbol. If this symbol is derived from another
/// symbol by (say) type substitution, this gets the original symbol, as it was defined in
/// source or metadata.
/// </summary>
new IFieldSymbol OriginalDefinition { get; }
/// <summary>
/// If this field represents a tuple element, returns a corresponding default element field.
/// Otherwise returns null.
/// </summary>
/// <remarks>
/// A tuple type will always have default elements such as Item1, Item2, Item3...
/// This API allows matching a field that represents a named element, such as "Alice"
/// to the corresponding default element field such as "Item1"
/// </remarks>
IFieldSymbol? CorrespondingTupleField { get; }
/// <summary>
/// Returns true if this field represents a tuple element which was given an explicit name.
/// </summary>
bool IsExplicitlyNamedTupleElement { get; }
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.ReplacePropertyWithMethods;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ReplacePropertyWithMethods
{
[ExportLanguageService(typeof(IReplacePropertyWithMethodsService), LanguageNames.CSharp), Shared]
internal partial class CSharpReplacePropertyWithMethodsService :
AbstractReplacePropertyWithMethodsService<IdentifierNameSyntax, ExpressionSyntax, NameMemberCrefSyntax, StatementSyntax, PropertyDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpReplacePropertyWithMethodsService()
{
}
public override async Task<ImmutableArray<SyntaxNode>> GetReplacementMembersAsync(
Document document,
IPropertySymbol property,
SyntaxNode propertyDeclarationNode,
IFieldSymbol propertyBackingField,
string desiredGetMethodName,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
if (!(propertyDeclarationNode is PropertyDeclarationSyntax propertyDeclaration))
return ImmutableArray<SyntaxNode>.Empty;
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var parseOptions = syntaxTree.Options;
return ConvertPropertyToMembers(
documentOptions, parseOptions,
SyntaxGenerator.GetGenerator(document), property,
propertyDeclaration, propertyBackingField,
desiredGetMethodName, desiredSetMethodName,
cancellationToken);
}
private static ImmutableArray<SyntaxNode> ConvertPropertyToMembers(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxGenerator generator,
IPropertySymbol property,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
string desiredGetMethodName,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var result);
if (propertyBackingField != null)
{
var initializer = propertyDeclaration.Initializer?.Value;
result.Add(generator.FieldDeclaration(propertyBackingField, initializer));
}
var getMethod = property.GetMethod;
if (getMethod != null)
{
result.Add(GetGetMethod(
documentOptions, parseOptions,
generator, propertyDeclaration, propertyBackingField,
getMethod, desiredGetMethodName,
cancellationToken: cancellationToken));
}
var setMethod = property.SetMethod;
if (setMethod != null)
{
result.Add(GetSetMethod(
documentOptions, parseOptions,
generator, propertyDeclaration, propertyBackingField,
setMethod, desiredSetMethodName,
cancellationToken: cancellationToken));
}
return result.ToImmutable();
}
private static SyntaxNode GetSetMethod(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol setMethod,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
var methodDeclaration = GetSetMethodWorker(
generator, propertyDeclaration, propertyBackingField,
setMethod, desiredSetMethodName, cancellationToken);
// The analyzer doesn't report diagnostics when the trivia contains preprocessor directives, so it's safe
// to copy the complete leading trivia to both generated methods.
methodDeclaration = CopyLeadingTrivia(propertyDeclaration, methodDeclaration, ConvertValueToParamRewriter.Instance);
return UseExpressionOrBlockBodyIfDesired(
documentOptions, parseOptions, methodDeclaration,
createReturnStatementForExpression: false);
}
private static MethodDeclarationSyntax GetSetMethodWorker(
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol setMethod,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
var setAccessorDeclaration = (AccessorDeclarationSyntax)setMethod.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken);
var methodDeclaration = (MethodDeclarationSyntax)generator.MethodDeclaration(setMethod, desiredSetMethodName);
// property has unsafe, but generator didn't add it to the method, so we have to add it here
if (propertyDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword)
&& !methodDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword))
{
methodDeclaration = methodDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
if (setAccessorDeclaration.Body != null)
{
return methodDeclaration.WithBody(setAccessorDeclaration.Body)
.WithAdditionalAnnotations(Formatter.Annotation);
}
else if (setAccessorDeclaration.ExpressionBody != null)
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(setAccessorDeclaration.ExpressionBody)
.WithSemicolonToken(setAccessorDeclaration.SemicolonToken);
}
else if (propertyBackingField != null)
{
return methodDeclaration.WithBody(SyntaxFactory.Block(
(StatementSyntax)generator.ExpressionStatement(
generator.AssignmentStatement(
GetFieldReference(generator, propertyBackingField),
generator.IdentifierName("value")))));
}
return methodDeclaration;
}
private static SyntaxNode GetGetMethod(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol getMethod,
string desiredGetMethodName,
CancellationToken cancellationToken)
{
var methodDeclaration = GetGetMethodWorker(
generator, propertyDeclaration, propertyBackingField, getMethod,
desiredGetMethodName, cancellationToken);
methodDeclaration = CopyLeadingTrivia(propertyDeclaration, methodDeclaration, ConvertValueToReturnsRewriter.Instance);
return UseExpressionOrBlockBodyIfDesired(
documentOptions, parseOptions, methodDeclaration,
createReturnStatementForExpression: true);
}
private static MethodDeclarationSyntax CopyLeadingTrivia(
PropertyDeclarationSyntax propertyDeclaration,
MethodDeclarationSyntax methodDeclaration,
CSharpSyntaxRewriter documentationCommentRewriter)
{
var leadingTrivia = propertyDeclaration.GetLeadingTrivia();
return methodDeclaration.WithLeadingTrivia(leadingTrivia.Select(trivia => ConvertTrivia(trivia, documentationCommentRewriter)));
}
private static SyntaxTrivia ConvertTrivia(SyntaxTrivia trivia, CSharpSyntaxRewriter rewriter)
{
if (trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia ||
trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
{
return ConvertDocumentationComment(trivia, rewriter);
}
return trivia;
}
private static SyntaxTrivia ConvertDocumentationComment(SyntaxTrivia trivia, CSharpSyntaxRewriter rewriter)
{
var structure = trivia.GetStructure();
var rewritten = rewriter.Visit(structure);
Contract.ThrowIfNull(rewritten);
return SyntaxFactory.Trivia((StructuredTriviaSyntax)rewritten);
}
private static SyntaxNode UseExpressionOrBlockBodyIfDesired(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
MethodDeclarationSyntax methodDeclaration, bool createReturnStatementForExpression)
{
var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value;
if (methodDeclaration.Body != null && expressionBodyPreference != ExpressionBodyPreference.Never)
{
if (methodDeclaration.Body.TryConvertToArrowExpressionBody(
methodDeclaration.Kind(), parseOptions, expressionBodyPreference,
out var arrowExpression, out var semicolonToken))
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(arrowExpression)
.WithSemicolonToken(semicolonToken)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
else if (methodDeclaration.ExpressionBody != null && expressionBodyPreference == ExpressionBodyPreference.Never)
{
if (methodDeclaration.ExpressionBody.TryConvertToBlock(
methodDeclaration.SemicolonToken, createReturnStatementForExpression, out var block))
{
return methodDeclaration.WithExpressionBody(null)
.WithSemicolonToken(default)
.WithBody(block)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
return methodDeclaration;
}
private static MethodDeclarationSyntax GetGetMethodWorker(
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol getMethod,
string desiredGetMethodName,
CancellationToken cancellationToken)
{
var methodDeclaration = (MethodDeclarationSyntax)generator.MethodDeclaration(getMethod, desiredGetMethodName);
// property has unsafe, but generator didn't add it to the method, so we have to add it here
if (propertyDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword)
&& !methodDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword))
{
methodDeclaration = methodDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
if (propertyDeclaration.ExpressionBody != null)
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(propertyDeclaration.ExpressionBody)
.WithSemicolonToken(propertyDeclaration.SemicolonToken);
}
else
{
var getAccessorDeclaration = (AccessorDeclarationSyntax)getMethod.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken);
if (getAccessorDeclaration?.ExpressionBody != null)
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(getAccessorDeclaration.ExpressionBody)
.WithSemicolonToken(getAccessorDeclaration.SemicolonToken);
}
if (getAccessorDeclaration?.Body != null)
{
return methodDeclaration.WithBody(getAccessorDeclaration.Body)
.WithAdditionalAnnotations(Formatter.Annotation);
}
else if (propertyBackingField != null)
{
var fieldReference = GetFieldReference(generator, propertyBackingField);
return methodDeclaration.WithBody(
SyntaxFactory.Block(
(StatementSyntax)generator.ReturnStatement(fieldReference)));
}
}
return methodDeclaration;
}
/// <summary>
/// Used by the documentation comment rewriters to identify top-level <c><value></c> nodes.
/// </summary>
private static bool IsValueName(XmlNameSyntax name)
=> name.Prefix == null &&
name.LocalName.ValueText == "value";
public override SyntaxNode GetPropertyNodeToReplace(SyntaxNode propertyDeclaration)
{
// For C# we'll have the property declaration that we want to replace.
return propertyDeclaration;
}
protected override NameMemberCrefSyntax? TryGetCrefSyntax(IdentifierNameSyntax identifierName)
=> identifierName.Parent as NameMemberCrefSyntax;
protected override NameMemberCrefSyntax CreateCrefSyntax(NameMemberCrefSyntax originalCref, SyntaxToken identifierToken, SyntaxNode? parameterType)
{
CrefParameterListSyntax parameterList;
if (parameterType is TypeSyntax typeSyntax)
{
var parameter = SyntaxFactory.CrefParameter(typeSyntax);
parameterList = SyntaxFactory.CrefParameterList(SyntaxFactory.SingletonSeparatedList(parameter));
}
else
{
parameterList = SyntaxFactory.CrefParameterList();
}
// XmlCrefAttribute replaces <T> with {T}, which is required for C# documentation comments
var crefAttribute = SyntaxFactory.XmlCrefAttribute(
SyntaxFactory.NameMemberCref(SyntaxFactory.IdentifierName(identifierToken), parameterList));
return (NameMemberCrefSyntax)crefAttribute.Cref;
}
protected override ExpressionSyntax UnwrapCompoundAssignment(
SyntaxNode compoundAssignment, ExpressionSyntax readExpression)
{
var parent = (AssignmentExpressionSyntax)compoundAssignment;
var operatorKind =
parent.IsKind(SyntaxKind.OrAssignmentExpression) ? SyntaxKind.BitwiseOrExpression :
parent.IsKind(SyntaxKind.AndAssignmentExpression) ? SyntaxKind.BitwiseAndExpression :
parent.IsKind(SyntaxKind.ExclusiveOrAssignmentExpression) ? SyntaxKind.ExclusiveOrExpression :
parent.IsKind(SyntaxKind.LeftShiftAssignmentExpression) ? SyntaxKind.LeftShiftExpression :
parent.IsKind(SyntaxKind.RightShiftAssignmentExpression) ? SyntaxKind.RightShiftExpression :
parent.IsKind(SyntaxKind.AddAssignmentExpression) ? SyntaxKind.AddExpression :
parent.IsKind(SyntaxKind.SubtractAssignmentExpression) ? SyntaxKind.SubtractExpression :
parent.IsKind(SyntaxKind.MultiplyAssignmentExpression) ? SyntaxKind.MultiplyExpression :
parent.IsKind(SyntaxKind.DivideAssignmentExpression) ? SyntaxKind.DivideExpression :
parent.IsKind(SyntaxKind.ModuloAssignmentExpression) ? SyntaxKind.ModuloExpression : SyntaxKind.None;
return SyntaxFactory.BinaryExpression(operatorKind, readExpression, parent.Right.Parenthesize());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.ReplacePropertyWithMethods;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ReplacePropertyWithMethods
{
[ExportLanguageService(typeof(IReplacePropertyWithMethodsService), LanguageNames.CSharp), Shared]
internal partial class CSharpReplacePropertyWithMethodsService :
AbstractReplacePropertyWithMethodsService<IdentifierNameSyntax, ExpressionSyntax, NameMemberCrefSyntax, StatementSyntax, PropertyDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpReplacePropertyWithMethodsService()
{
}
public override async Task<ImmutableArray<SyntaxNode>> GetReplacementMembersAsync(
Document document,
IPropertySymbol property,
SyntaxNode propertyDeclarationNode,
IFieldSymbol propertyBackingField,
string desiredGetMethodName,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
if (!(propertyDeclarationNode is PropertyDeclarationSyntax propertyDeclaration))
return ImmutableArray<SyntaxNode>.Empty;
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var parseOptions = syntaxTree.Options;
return ConvertPropertyToMembers(
documentOptions, parseOptions,
SyntaxGenerator.GetGenerator(document), property,
propertyDeclaration, propertyBackingField,
desiredGetMethodName, desiredSetMethodName,
cancellationToken);
}
private static ImmutableArray<SyntaxNode> ConvertPropertyToMembers(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxGenerator generator,
IPropertySymbol property,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
string desiredGetMethodName,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var result);
if (propertyBackingField != null)
{
var initializer = propertyDeclaration.Initializer?.Value;
result.Add(generator.FieldDeclaration(propertyBackingField, initializer));
}
var getMethod = property.GetMethod;
if (getMethod != null)
{
result.Add(GetGetMethod(
documentOptions, parseOptions,
generator, propertyDeclaration, propertyBackingField,
getMethod, desiredGetMethodName,
cancellationToken: cancellationToken));
}
var setMethod = property.SetMethod;
if (setMethod != null)
{
result.Add(GetSetMethod(
documentOptions, parseOptions,
generator, propertyDeclaration, propertyBackingField,
setMethod, desiredSetMethodName,
cancellationToken: cancellationToken));
}
return result.ToImmutable();
}
private static SyntaxNode GetSetMethod(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol setMethod,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
var methodDeclaration = GetSetMethodWorker(
generator, propertyDeclaration, propertyBackingField,
setMethod, desiredSetMethodName, cancellationToken);
// The analyzer doesn't report diagnostics when the trivia contains preprocessor directives, so it's safe
// to copy the complete leading trivia to both generated methods.
methodDeclaration = CopyLeadingTrivia(propertyDeclaration, methodDeclaration, ConvertValueToParamRewriter.Instance);
return UseExpressionOrBlockBodyIfDesired(
documentOptions, parseOptions, methodDeclaration,
createReturnStatementForExpression: false);
}
private static MethodDeclarationSyntax GetSetMethodWorker(
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol setMethod,
string desiredSetMethodName,
CancellationToken cancellationToken)
{
var setAccessorDeclaration = (AccessorDeclarationSyntax)setMethod.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken);
var methodDeclaration = (MethodDeclarationSyntax)generator.MethodDeclaration(setMethod, desiredSetMethodName);
// property has unsafe, but generator didn't add it to the method, so we have to add it here
if (propertyDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword)
&& !methodDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword))
{
methodDeclaration = methodDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
if (setAccessorDeclaration.Body != null)
{
return methodDeclaration.WithBody(setAccessorDeclaration.Body)
.WithAdditionalAnnotations(Formatter.Annotation);
}
else if (setAccessorDeclaration.ExpressionBody != null)
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(setAccessorDeclaration.ExpressionBody)
.WithSemicolonToken(setAccessorDeclaration.SemicolonToken);
}
else if (propertyBackingField != null)
{
return methodDeclaration.WithBody(SyntaxFactory.Block(
(StatementSyntax)generator.ExpressionStatement(
generator.AssignmentStatement(
GetFieldReference(generator, propertyBackingField),
generator.IdentifierName("value")))));
}
return methodDeclaration;
}
private static SyntaxNode GetGetMethod(
DocumentOptionSet documentOptions,
ParseOptions parseOptions,
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol getMethod,
string desiredGetMethodName,
CancellationToken cancellationToken)
{
var methodDeclaration = GetGetMethodWorker(
generator, propertyDeclaration, propertyBackingField, getMethod,
desiredGetMethodName, cancellationToken);
methodDeclaration = CopyLeadingTrivia(propertyDeclaration, methodDeclaration, ConvertValueToReturnsRewriter.Instance);
return UseExpressionOrBlockBodyIfDesired(
documentOptions, parseOptions, methodDeclaration,
createReturnStatementForExpression: true);
}
private static MethodDeclarationSyntax CopyLeadingTrivia(
PropertyDeclarationSyntax propertyDeclaration,
MethodDeclarationSyntax methodDeclaration,
CSharpSyntaxRewriter documentationCommentRewriter)
{
var leadingTrivia = propertyDeclaration.GetLeadingTrivia();
return methodDeclaration.WithLeadingTrivia(leadingTrivia.Select(trivia => ConvertTrivia(trivia, documentationCommentRewriter)));
}
private static SyntaxTrivia ConvertTrivia(SyntaxTrivia trivia, CSharpSyntaxRewriter rewriter)
{
if (trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia ||
trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia)
{
return ConvertDocumentationComment(trivia, rewriter);
}
return trivia;
}
private static SyntaxTrivia ConvertDocumentationComment(SyntaxTrivia trivia, CSharpSyntaxRewriter rewriter)
{
var structure = trivia.GetStructure();
var rewritten = rewriter.Visit(structure);
Contract.ThrowIfNull(rewritten);
return SyntaxFactory.Trivia((StructuredTriviaSyntax)rewritten);
}
private static SyntaxNode UseExpressionOrBlockBodyIfDesired(
DocumentOptionSet documentOptions, ParseOptions parseOptions,
MethodDeclarationSyntax methodDeclaration, bool createReturnStatementForExpression)
{
var expressionBodyPreference = documentOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value;
if (methodDeclaration.Body != null && expressionBodyPreference != ExpressionBodyPreference.Never)
{
if (methodDeclaration.Body.TryConvertToArrowExpressionBody(
methodDeclaration.Kind(), parseOptions, expressionBodyPreference,
out var arrowExpression, out var semicolonToken))
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(arrowExpression)
.WithSemicolonToken(semicolonToken)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
else if (methodDeclaration.ExpressionBody != null && expressionBodyPreference == ExpressionBodyPreference.Never)
{
if (methodDeclaration.ExpressionBody.TryConvertToBlock(
methodDeclaration.SemicolonToken, createReturnStatementForExpression, out var block))
{
return methodDeclaration.WithExpressionBody(null)
.WithSemicolonToken(default)
.WithBody(block)
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
return methodDeclaration;
}
private static MethodDeclarationSyntax GetGetMethodWorker(
SyntaxGenerator generator,
PropertyDeclarationSyntax propertyDeclaration,
IFieldSymbol? propertyBackingField,
IMethodSymbol getMethod,
string desiredGetMethodName,
CancellationToken cancellationToken)
{
var methodDeclaration = (MethodDeclarationSyntax)generator.MethodDeclaration(getMethod, desiredGetMethodName);
// property has unsafe, but generator didn't add it to the method, so we have to add it here
if (propertyDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword)
&& !methodDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword))
{
methodDeclaration = methodDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
if (propertyDeclaration.ExpressionBody != null)
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(propertyDeclaration.ExpressionBody)
.WithSemicolonToken(propertyDeclaration.SemicolonToken);
}
else
{
var getAccessorDeclaration = (AccessorDeclarationSyntax)getMethod.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken);
if (getAccessorDeclaration?.ExpressionBody != null)
{
return methodDeclaration.WithBody(null)
.WithExpressionBody(getAccessorDeclaration.ExpressionBody)
.WithSemicolonToken(getAccessorDeclaration.SemicolonToken);
}
if (getAccessorDeclaration?.Body != null)
{
return methodDeclaration.WithBody(getAccessorDeclaration.Body)
.WithAdditionalAnnotations(Formatter.Annotation);
}
else if (propertyBackingField != null)
{
var fieldReference = GetFieldReference(generator, propertyBackingField);
return methodDeclaration.WithBody(
SyntaxFactory.Block(
(StatementSyntax)generator.ReturnStatement(fieldReference)));
}
}
return methodDeclaration;
}
/// <summary>
/// Used by the documentation comment rewriters to identify top-level <c><value></c> nodes.
/// </summary>
private static bool IsValueName(XmlNameSyntax name)
=> name.Prefix == null &&
name.LocalName.ValueText == "value";
public override SyntaxNode GetPropertyNodeToReplace(SyntaxNode propertyDeclaration)
{
// For C# we'll have the property declaration that we want to replace.
return propertyDeclaration;
}
protected override NameMemberCrefSyntax? TryGetCrefSyntax(IdentifierNameSyntax identifierName)
=> identifierName.Parent as NameMemberCrefSyntax;
protected override NameMemberCrefSyntax CreateCrefSyntax(NameMemberCrefSyntax originalCref, SyntaxToken identifierToken, SyntaxNode? parameterType)
{
CrefParameterListSyntax parameterList;
if (parameterType is TypeSyntax typeSyntax)
{
var parameter = SyntaxFactory.CrefParameter(typeSyntax);
parameterList = SyntaxFactory.CrefParameterList(SyntaxFactory.SingletonSeparatedList(parameter));
}
else
{
parameterList = SyntaxFactory.CrefParameterList();
}
// XmlCrefAttribute replaces <T> with {T}, which is required for C# documentation comments
var crefAttribute = SyntaxFactory.XmlCrefAttribute(
SyntaxFactory.NameMemberCref(SyntaxFactory.IdentifierName(identifierToken), parameterList));
return (NameMemberCrefSyntax)crefAttribute.Cref;
}
protected override ExpressionSyntax UnwrapCompoundAssignment(
SyntaxNode compoundAssignment, ExpressionSyntax readExpression)
{
var parent = (AssignmentExpressionSyntax)compoundAssignment;
var operatorKind =
parent.IsKind(SyntaxKind.OrAssignmentExpression) ? SyntaxKind.BitwiseOrExpression :
parent.IsKind(SyntaxKind.AndAssignmentExpression) ? SyntaxKind.BitwiseAndExpression :
parent.IsKind(SyntaxKind.ExclusiveOrAssignmentExpression) ? SyntaxKind.ExclusiveOrExpression :
parent.IsKind(SyntaxKind.LeftShiftAssignmentExpression) ? SyntaxKind.LeftShiftExpression :
parent.IsKind(SyntaxKind.RightShiftAssignmentExpression) ? SyntaxKind.RightShiftExpression :
parent.IsKind(SyntaxKind.AddAssignmentExpression) ? SyntaxKind.AddExpression :
parent.IsKind(SyntaxKind.SubtractAssignmentExpression) ? SyntaxKind.SubtractExpression :
parent.IsKind(SyntaxKind.MultiplyAssignmentExpression) ? SyntaxKind.MultiplyExpression :
parent.IsKind(SyntaxKind.DivideAssignmentExpression) ? SyntaxKind.DivideExpression :
parent.IsKind(SyntaxKind.ModuloAssignmentExpression) ? SyntaxKind.ModuloExpression : SyntaxKind.None;
return SyntaxFactory.BinaryExpression(operatorKind, readExpression, parent.Right.Parenthesize());
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/ModernCommands/GoToImplementationCommandArgs.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Go To Implementation.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class GoToImplementationCommandArgs : EditorCommandArgs
{
public GoToImplementationCommandArgs(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 Go To Implementation.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class GoToImplementationCommandArgs : EditorCommandArgs
{
public GoToImplementationCommandArgs(ITextView textView, ITextBuffer subjectBuffer)
: base(textView, subjectBuffer)
{
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Implementation/TextStructureNavigation/AbstractTextStructureNavigatorProvider.TextStructureNavigator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TextStructureNavigation
{
internal partial class AbstractTextStructureNavigatorProvider
{
private class TextStructureNavigator : ITextStructureNavigator
{
private readonly ITextBuffer _subjectBuffer;
private readonly ITextStructureNavigator _naturalLanguageNavigator;
private readonly AbstractTextStructureNavigatorProvider _provider;
private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor;
internal TextStructureNavigator(
ITextBuffer subjectBuffer,
ITextStructureNavigator naturalLanguageNavigator,
AbstractTextStructureNavigatorProvider provider,
IUIThreadOperationExecutor uIThreadOperationExecutor)
{
Contract.ThrowIfNull(subjectBuffer);
Contract.ThrowIfNull(naturalLanguageNavigator);
Contract.ThrowIfNull(provider);
_subjectBuffer = subjectBuffer;
_naturalLanguageNavigator = naturalLanguageNavigator;
_provider = provider;
_uiThreadOperationExecutor = uIThreadOperationExecutor;
}
public IContentType ContentType => _subjectBuffer.ContentType;
public TextExtent GetExtentOfWord(SnapshotPoint currentPosition)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetExtentOfWord, CancellationToken.None))
{
var result = default(TextExtent);
_uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_word_extent,
allowCancellation: true,
showProgress: false,
action: context =>
{
result = GetExtentOfWordWorker(currentPosition, context.UserCancellationToken);
});
return result;
}
}
private TextExtent GetExtentOfWordWorker(SnapshotPoint position, CancellationToken cancellationToken)
{
var textLength = position.Snapshot.Length;
if (textLength == 0)
{
return _naturalLanguageNavigator.GetExtentOfWord(position);
}
// If at the end of the file, go back one character so stuff works
if (position == textLength && position > 0)
{
position -= 1;
}
// If we're at the EOL position, return the line break's extent
var line = position.Snapshot.GetLineFromPosition(position);
if (position >= line.End && position < line.EndIncludingLineBreak)
{
return new TextExtent(new SnapshotSpan(line.End, line.EndIncludingLineBreak - line.End), isSignificant: false);
}
var document = GetDocument(position);
if (document != null)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var trivia = root.FindTrivia(position, findInsideTrivia: true);
if (trivia != default)
{
if (trivia.Span.Start == position && _provider.ShouldSelectEntireTriviaFromStart(trivia))
{
// We want to select the entire comment
return new TextExtent(trivia.Span.ToSnapshotSpan(position.Snapshot), isSignificant: true);
}
}
var token = root.FindToken(position, findInsideTrivia: true);
// If end of file, go back a token
if (token.Span.Length == 0 && token.Span.Start == textLength)
{
token = token.GetPreviousToken();
}
if (token.Span.Length > 0 && token.Span.Contains(position) && !_provider.IsWithinNaturalLanguage(token, position))
{
// Cursor position is in our domain - handle it.
return _provider.GetExtentOfWordFromToken(token, position);
}
}
// Fall back to natural language navigator do its thing.
return _naturalLanguageNavigator.GetExtentOfWord(position);
}
public SnapshotSpan GetSpanOfEnclosing(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfEnclosing, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_enclosing_span,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfEnclosingWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfEnclosingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null && activeSpan.Length == node.Value.Span.Length)
{
// Go one level up so the span widens.
node = GetEnclosingNode(node.Value);
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfFirstChild(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfFirstChild, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_enclosing_span,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfFirstChildWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfFirstChildWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Take first child if possible, otherwise default to node itself.
var firstChild = node.Value.ChildNodesAndTokens().FirstOrNull();
if (firstChild.HasValue)
{
node = firstChild.Value;
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfNextSibling(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfNextSibling, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_span_of_next_sibling,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfNextSiblingWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfNextSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Get ancestor with a wider span.
var parent = GetEnclosingNode(node.Value);
if (parent != null)
{
// Find node immediately after the current in the children collection.
var nodeOrToken = parent.Value
.ChildNodesAndTokens()
.SkipWhile(child => child != node)
.Skip(1)
.FirstOrNull();
if (nodeOrToken.HasValue)
{
node = nodeOrToken.Value;
}
else
{
// If this is the last node, move to the parent so that the user can continue
// navigation at the higher level.
node = parent.Value;
}
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfPreviousSibling(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfPreviousSibling, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_span_of_previous_sibling,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfPreviousSiblingWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfPreviousSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Get ancestor with a wider span.
var parent = GetEnclosingNode(node.Value);
if (parent != null)
{
// Find node immediately before the current in the children collection.
var nodeOrToken = parent.Value
.ChildNodesAndTokens()
.Reverse()
.SkipWhile(child => child != node)
.Skip(1)
.FirstOrNull();
if (nodeOrToken.HasValue)
{
node = nodeOrToken.Value;
}
else
{
// If this is the first node, move to the parent so that the user can continue
// navigation at the higher level.
node = parent.Value;
}
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
private static Document GetDocument(SnapshotPoint point)
{
var textLength = point.Snapshot.Length;
if (textLength == 0)
{
return null;
}
return point.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
}
/// <summary>
/// Finds deepest node that covers given <see cref="SnapshotSpan"/>.
/// </summary>
private static SyntaxNodeOrToken? FindLeafNode(SnapshotSpan span, CancellationToken cancellationToken)
{
if (!TryFindLeafToken(span.Start, out var token, cancellationToken))
{
return null;
}
SyntaxNodeOrToken? node = token;
while (node != null && (span.End.Position > node.Value.Span.End))
{
node = GetEnclosingNode(node.Value);
}
return node;
}
/// <summary>
/// Given position in a text buffer returns the leaf syntax node it belongs to.
/// </summary>
private static bool TryFindLeafToken(SnapshotPoint point, out SyntaxToken token, CancellationToken cancellationToken)
{
var syntaxTree = GetDocument(point).GetSyntaxTreeSynchronously(cancellationToken);
if (syntaxTree != null)
{
token = syntaxTree.GetRoot(cancellationToken).FindToken(point, true);
return true;
}
token = default;
return false;
}
/// <summary>
/// Returns first ancestor of the node which has a span wider than node's span.
/// If none exist, returns the last available ancestor.
/// </summary>
private static SyntaxNodeOrToken SkipSameSpanParents(SyntaxNodeOrToken node)
{
while (node.Parent != null && node.Parent.Span == node.Span)
{
node = node.Parent;
}
return node;
}
/// <summary>
/// Finds node enclosing current from navigation point of view (that is, some immediate ancestors
/// may be skipped during this process).
/// </summary>
private static SyntaxNodeOrToken? GetEnclosingNode(SyntaxNodeOrToken node)
{
var parent = SkipSameSpanParents(node).Parent;
if (parent != null)
{
return parent;
}
else
{
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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TextStructureNavigation
{
internal partial class AbstractTextStructureNavigatorProvider
{
private class TextStructureNavigator : ITextStructureNavigator
{
private readonly ITextBuffer _subjectBuffer;
private readonly ITextStructureNavigator _naturalLanguageNavigator;
private readonly AbstractTextStructureNavigatorProvider _provider;
private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor;
internal TextStructureNavigator(
ITextBuffer subjectBuffer,
ITextStructureNavigator naturalLanguageNavigator,
AbstractTextStructureNavigatorProvider provider,
IUIThreadOperationExecutor uIThreadOperationExecutor)
{
Contract.ThrowIfNull(subjectBuffer);
Contract.ThrowIfNull(naturalLanguageNavigator);
Contract.ThrowIfNull(provider);
_subjectBuffer = subjectBuffer;
_naturalLanguageNavigator = naturalLanguageNavigator;
_provider = provider;
_uiThreadOperationExecutor = uIThreadOperationExecutor;
}
public IContentType ContentType => _subjectBuffer.ContentType;
public TextExtent GetExtentOfWord(SnapshotPoint currentPosition)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetExtentOfWord, CancellationToken.None))
{
var result = default(TextExtent);
_uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_word_extent,
allowCancellation: true,
showProgress: false,
action: context =>
{
result = GetExtentOfWordWorker(currentPosition, context.UserCancellationToken);
});
return result;
}
}
private TextExtent GetExtentOfWordWorker(SnapshotPoint position, CancellationToken cancellationToken)
{
var textLength = position.Snapshot.Length;
if (textLength == 0)
{
return _naturalLanguageNavigator.GetExtentOfWord(position);
}
// If at the end of the file, go back one character so stuff works
if (position == textLength && position > 0)
{
position -= 1;
}
// If we're at the EOL position, return the line break's extent
var line = position.Snapshot.GetLineFromPosition(position);
if (position >= line.End && position < line.EndIncludingLineBreak)
{
return new TextExtent(new SnapshotSpan(line.End, line.EndIncludingLineBreak - line.End), isSignificant: false);
}
var document = GetDocument(position);
if (document != null)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var trivia = root.FindTrivia(position, findInsideTrivia: true);
if (trivia != default)
{
if (trivia.Span.Start == position && _provider.ShouldSelectEntireTriviaFromStart(trivia))
{
// We want to select the entire comment
return new TextExtent(trivia.Span.ToSnapshotSpan(position.Snapshot), isSignificant: true);
}
}
var token = root.FindToken(position, findInsideTrivia: true);
// If end of file, go back a token
if (token.Span.Length == 0 && token.Span.Start == textLength)
{
token = token.GetPreviousToken();
}
if (token.Span.Length > 0 && token.Span.Contains(position) && !_provider.IsWithinNaturalLanguage(token, position))
{
// Cursor position is in our domain - handle it.
return _provider.GetExtentOfWordFromToken(token, position);
}
}
// Fall back to natural language navigator do its thing.
return _naturalLanguageNavigator.GetExtentOfWord(position);
}
public SnapshotSpan GetSpanOfEnclosing(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfEnclosing, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_enclosing_span,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfEnclosingWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfEnclosingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null && activeSpan.Length == node.Value.Span.Length)
{
// Go one level up so the span widens.
node = GetEnclosingNode(node.Value);
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfFirstChild(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfFirstChild, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_enclosing_span,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfFirstChildWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfFirstChildWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Take first child if possible, otherwise default to node itself.
var firstChild = node.Value.ChildNodesAndTokens().FirstOrNull();
if (firstChild.HasValue)
{
node = firstChild.Value;
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfNextSibling(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfNextSibling, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_span_of_next_sibling,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfNextSiblingWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfNextSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Get ancestor with a wider span.
var parent = GetEnclosingNode(node.Value);
if (parent != null)
{
// Find node immediately after the current in the children collection.
var nodeOrToken = parent.Value
.ChildNodesAndTokens()
.SkipWhile(child => child != node)
.Skip(1)
.FirstOrNull();
if (nodeOrToken.HasValue)
{
node = nodeOrToken.Value;
}
else
{
// If this is the last node, move to the parent so that the user can continue
// navigation at the higher level.
node = parent.Value;
}
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfPreviousSibling(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfPreviousSibling, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _uiThreadOperationExecutor.Execute(
title: EditorFeaturesResources.Text_Navigation,
defaultDescription: EditorFeaturesResources.Finding_span_of_previous_sibling,
allowCancellation: true,
showProgress: false,
action: context =>
{
span = GetSpanOfPreviousSiblingWorker(activeSpan, context.UserCancellationToken);
});
return result == UIThreadOperationStatus.Completed ? span : activeSpan;
}
}
private static SnapshotSpan GetSpanOfPreviousSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Get ancestor with a wider span.
var parent = GetEnclosingNode(node.Value);
if (parent != null)
{
// Find node immediately before the current in the children collection.
var nodeOrToken = parent.Value
.ChildNodesAndTokens()
.Reverse()
.SkipWhile(child => child != node)
.Skip(1)
.FirstOrNull();
if (nodeOrToken.HasValue)
{
node = nodeOrToken.Value;
}
else
{
// If this is the first node, move to the parent so that the user can continue
// navigation at the higher level.
node = parent.Value;
}
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
private static Document GetDocument(SnapshotPoint point)
{
var textLength = point.Snapshot.Length;
if (textLength == 0)
{
return null;
}
return point.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
}
/// <summary>
/// Finds deepest node that covers given <see cref="SnapshotSpan"/>.
/// </summary>
private static SyntaxNodeOrToken? FindLeafNode(SnapshotSpan span, CancellationToken cancellationToken)
{
if (!TryFindLeafToken(span.Start, out var token, cancellationToken))
{
return null;
}
SyntaxNodeOrToken? node = token;
while (node != null && (span.End.Position > node.Value.Span.End))
{
node = GetEnclosingNode(node.Value);
}
return node;
}
/// <summary>
/// Given position in a text buffer returns the leaf syntax node it belongs to.
/// </summary>
private static bool TryFindLeafToken(SnapshotPoint point, out SyntaxToken token, CancellationToken cancellationToken)
{
var syntaxTree = GetDocument(point).GetSyntaxTreeSynchronously(cancellationToken);
if (syntaxTree != null)
{
token = syntaxTree.GetRoot(cancellationToken).FindToken(point, true);
return true;
}
token = default;
return false;
}
/// <summary>
/// Returns first ancestor of the node which has a span wider than node's span.
/// If none exist, returns the last available ancestor.
/// </summary>
private static SyntaxNodeOrToken SkipSameSpanParents(SyntaxNodeOrToken node)
{
while (node.Parent != null && node.Parent.Span == node.Span)
{
node = node.Parent;
}
return node;
}
/// <summary>
/// Finds node enclosing current from navigation point of view (that is, some immediate ancestors
/// may be skipped during this process).
/// </summary>
private static SyntaxNodeOrToken? GetEnclosingNode(SyntaxNodeOrToken node)
{
var parent = SkipSameSpanParents(node).Parent;
if (parent != null)
{
return parent;
}
else
{
return null;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/CSharp/Test/CodeModel/FileCodeImportTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeImportTests : AbstractFileCodeElementTests
{
public FileCodeImportTests()
: base(@"using System;
using Goo = System.Data;")
{
}
private CodeImport GetCodeImport(object path)
{
return (CodeImport)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Name()
{
var import = GetCodeImport(1);
Assert.Throws<COMException>(() => { var value = import.Name; });
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FullName()
{
var import = GetCodeImport(1);
Assert.Throws<COMException>(() => { var value = import.FullName; });
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Kind()
{
var import = GetCodeImport(1);
Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Namespace()
{
var import = GetCodeImport(1);
Assert.Equal("System", import.Namespace);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Alias()
{
var import = GetCodeImport(2);
Assert.Equal("Goo", import.Alias);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var import = GetCodeImport(2);
var startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, startPoint.Line);
Assert.Equal(13, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var import = GetCodeImport(2);
var startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var import = GetCodeImport(2);
var endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, endPoint.Line);
Assert.Equal(24, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var import = GetCodeImport(2);
var endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var import = GetCodeImport(2);
var startPoint = import.StartPoint;
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var import = GetCodeImport(2);
var endPoint = import.EndPoint;
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using EnvDTE;
using EnvDTE80;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeImportTests : AbstractFileCodeElementTests
{
public FileCodeImportTests()
: base(@"using System;
using Goo = System.Data;")
{
}
private CodeImport GetCodeImport(object path)
{
return (CodeImport)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Name()
{
var import = GetCodeImport(1);
Assert.Throws<COMException>(() => { var value = import.Name; });
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void FullName()
{
var import = GetCodeImport(1);
Assert.Throws<COMException>(() => { var value = import.FullName; });
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Kind()
{
var import = GetCodeImport(1);
Assert.Equal(vsCMElement.vsCMElementImportStmt, import.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Namespace()
{
var import = GetCodeImport(1);
Assert.Equal("System", import.Namespace);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Alias()
{
var import = GetCodeImport(2);
Assert.Equal("Goo", import.Alias);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetStartPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var import = GetCodeImport(2);
var startPoint = import.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, startPoint.Line);
Assert.Equal(13, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var import = GetCodeImport(2);
var startPoint = import.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var import = GetCodeImport(2);
Assert.Throws<COMException>(() => import.GetEndPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var import = GetCodeImport(2);
var endPoint = import.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(2, endPoint.Line);
Assert.Equal(24, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var import = GetCodeImport(2);
Assert.Throws<NotImplementedException>(() => import.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var import = GetCodeImport(2);
var endPoint = import.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var import = GetCodeImport(2);
var startPoint = import.StartPoint;
Assert.Equal(2, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var import = GetCodeImport(2);
var endPoint = import.EndPoint;
Assert.Equal(2, endPoint.Line);
Assert.Equal(25, endPoint.LineCharOffset);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CoreTest/UtilityTest/CancellationSeriesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/project-system:
// https://github.com/dotnet/project-system/blob/bdf69d5420ec8d894f5bf4c3d4692900b7f2479c/tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Threading/Tasks/CancellationSeriesTests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Linq;
using System.Threading;
using Xunit;
namespace Roslyn.Utilities
{
public sealed class CancellationSeriesTests
{
[Fact]
public void CreateNext_ReturnsNonCancelledToken()
{
using var series = new CancellationSeries();
var token = series.CreateNext();
Assert.False(token.IsCancellationRequested);
Assert.True(token.CanBeCanceled);
}
[Fact]
public void CreateNext_CancelsPreviousToken()
{
using var series = new CancellationSeries();
var token1 = series.CreateNext();
Assert.False(token1.IsCancellationRequested);
var token2 = series.CreateNext();
Assert.True(token1.IsCancellationRequested);
Assert.False(token2.IsCancellationRequested);
var token3 = series.CreateNext();
Assert.True(token2.IsCancellationRequested);
Assert.False(token3.IsCancellationRequested);
}
[Fact]
public void CreateNext_ThrowsIfDisposed()
{
var series = new CancellationSeries();
series.Dispose();
Assert.Throws<ObjectDisposedException>(() => series.CreateNext());
}
[Fact]
public void CreateNext_ReturnsCancelledTokenIfSuperTokenAlreadyCancelled()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries(cts.Token);
cts.Cancel();
var token = series.CreateNext();
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CreateNext_ReturnsCancelledTokenIfInputTokenAlreadyCancelled()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries();
cts.Cancel();
var token = series.CreateNext(cts.Token);
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CancellingSuperTokenCancelsIssuedToken()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries(cts.Token);
var token = series.CreateNext();
Assert.False(token.IsCancellationRequested);
cts.Cancel();
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CancellingInputTokenCancelsIssuedToken()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries();
var token = series.CreateNext(cts.Token);
Assert.False(token.IsCancellationRequested);
cts.Cancel();
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CreateNext_HandlesExceptionsFromPreviousTokenRegistration()
{
using var series = new CancellationSeries();
var token1 = series.CreateNext();
var exception = new Exception();
token1.Register(() => throw exception);
var aggregateException = Assert.Throws<AggregateException>(() => series.CreateNext());
Assert.Same(exception, aggregateException.InnerExceptions.Single());
Assert.True(token1.IsCancellationRequested);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/project-system:
// https://github.com/dotnet/project-system/blob/bdf69d5420ec8d894f5bf4c3d4692900b7f2479c/tests/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/Threading/Tasks/CancellationSeriesTests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Linq;
using System.Threading;
using Xunit;
namespace Roslyn.Utilities
{
public sealed class CancellationSeriesTests
{
[Fact]
public void CreateNext_ReturnsNonCancelledToken()
{
using var series = new CancellationSeries();
var token = series.CreateNext();
Assert.False(token.IsCancellationRequested);
Assert.True(token.CanBeCanceled);
}
[Fact]
public void CreateNext_CancelsPreviousToken()
{
using var series = new CancellationSeries();
var token1 = series.CreateNext();
Assert.False(token1.IsCancellationRequested);
var token2 = series.CreateNext();
Assert.True(token1.IsCancellationRequested);
Assert.False(token2.IsCancellationRequested);
var token3 = series.CreateNext();
Assert.True(token2.IsCancellationRequested);
Assert.False(token3.IsCancellationRequested);
}
[Fact]
public void CreateNext_ThrowsIfDisposed()
{
var series = new CancellationSeries();
series.Dispose();
Assert.Throws<ObjectDisposedException>(() => series.CreateNext());
}
[Fact]
public void CreateNext_ReturnsCancelledTokenIfSuperTokenAlreadyCancelled()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries(cts.Token);
cts.Cancel();
var token = series.CreateNext();
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CreateNext_ReturnsCancelledTokenIfInputTokenAlreadyCancelled()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries();
cts.Cancel();
var token = series.CreateNext(cts.Token);
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CancellingSuperTokenCancelsIssuedToken()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries(cts.Token);
var token = series.CreateNext();
Assert.False(token.IsCancellationRequested);
cts.Cancel();
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CancellingInputTokenCancelsIssuedToken()
{
var cts = new CancellationTokenSource();
using var series = new CancellationSeries();
var token = series.CreateNext(cts.Token);
Assert.False(token.IsCancellationRequested);
cts.Cancel();
Assert.True(token.IsCancellationRequested);
}
[Fact]
public void CreateNext_HandlesExceptionsFromPreviousTokenRegistration()
{
using var series = new CancellationSeries();
var token1 = series.CreateNext();
var exception = new Exception();
token1.Register(() => throw exception);
var aggregateException = Assert.Throws<AggregateException>(() => series.CreateNext());
Assert.Same(exception, aggregateException.InnerExceptions.Single());
Assert.True(token1.IsCancellationRequested);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/LanguageServer/Protocol/Handler/Commands/AbstractExecuteWorkspaceCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Commands
{
internal abstract class AbstractExecuteWorkspaceCommandHandler : IRequestHandler<ExecuteCommandParams, object>
{
public string Method => GetRequestNameForCommandName(Command);
public abstract string Command { get; }
public abstract bool MutatesSolutionState { get; }
public abstract bool RequiresLSPSolution { get; }
public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(ExecuteCommandParams request);
public abstract Task<object> HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken);
public static string GetRequestNameForCommandName(string commandName) => $"{Methods.WorkspaceExecuteCommandName}/{commandName}";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Commands
{
internal abstract class AbstractExecuteWorkspaceCommandHandler : IRequestHandler<ExecuteCommandParams, object>
{
public string Method => GetRequestNameForCommandName(Command);
public abstract string Command { get; }
public abstract bool MutatesSolutionState { get; }
public abstract bool RequiresLSPSolution { get; }
public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(ExecuteCommandParams request);
public abstract Task<object> HandleRequestAsync(ExecuteCommandParams request, RequestContext context, CancellationToken cancellationToken);
public static string GetRequestNameForCommandName(string commandName) => $"{Methods.WorkspaceExecuteCommandName}/{commandName}";
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/IManageNamingStylesInfoDialogViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ObjectModel;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal interface IManageNamingStylesInfoDialogViewModel
{
ObservableCollection<INamingStylesInfoDialogViewModel> Items { get; }
string DialogTitle { get; }
void AddItem();
void RemoveItem(INamingStylesInfoDialogViewModel item);
void EditItem(INamingStylesInfoDialogViewModel item);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ObjectModel;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal interface IManageNamingStylesInfoDialogViewModel
{
ObservableCollection<INamingStylesInfoDialogViewModel> Items { get; }
string DialogTitle { get; }
void AddItem();
void RemoveItem(INamingStylesInfoDialogViewModel item);
void EditItem(INamingStylesInfoDialogViewModel item);
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/DebuggerIntelliSense/DebuggerTextView.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Windows;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense
{
internal partial class DebuggerTextView : IWpfTextView, IDebuggerTextView2, ITextView2
{
/// <summary>
/// The actual debugger view of the watch or immediate window that we're wrapping
/// </summary>
private readonly IWpfTextView _innerTextView;
private readonly IVsTextLines _debuggerTextLinesOpt;
private IMultiSelectionBroker _multiSelectionBroker;
// This name "CompletionRoot" is specified on the Editor side.
// Roslyn must match the name.
// The const should be removed with resolution of https://github.com/dotnet/roslyn/issues/31189
public const string CompletionRoot = nameof(CompletionRoot);
public DebuggerTextView(
IWpfTextView innerTextView,
IBufferGraph bufferGraph,
IVsTextLines debuggerTextLinesOpt,
bool isImmediateWindow)
{
_innerTextView = innerTextView;
_debuggerTextLinesOpt = debuggerTextLinesOpt;
BufferGraph = bufferGraph;
IsImmediateWindow = isImmediateWindow;
// The editor requires the current top buffer.
// TODO it seems to be a hack. It should be removed.
// Here is an issue to track: https://github.com/dotnet/roslyn/issues/31189
// Starting debugging for the second time, we already have the property set.
_innerTextView.Properties[CompletionRoot] = bufferGraph.TopBuffer;
}
/// <summary>
/// We basically replace the innerTextView's BufferGraph with our own custom projection graph
/// that projects the immediate window contents into a context buffer:
///
/// (1)
/// (2) (5)
/// (3) (6)
/// (4)
/// (1) Top level projection buffer - the subject buffer used by intellisense
/// (2/3) Currently a double projection buffer combo that elides away the ? in the immediate window, and may add some
/// boilerplate code to force an expression context.
/// (4) innerTextView.TextBuffer, what the user actually sees in the watch/immediate windows
/// (5) A read-only projection of (6)
/// (6) The context buffer which is typically a source file
///
/// </summary>
public IBufferGraph BufferGraph
{
get;
}
public bool IsImmediateWindow
{
get;
}
public uint StartBufferUpdate()
{
// null in unit tests
if (_debuggerTextLinesOpt == null)
{
return 0;
}
_debuggerTextLinesOpt.GetStateFlags(out var bufferFlags);
_debuggerTextLinesOpt.SetStateFlags((uint)((BUFFERSTATEFLAGS)bufferFlags & ~BUFFERSTATEFLAGS.BSF_USER_READONLY));
return bufferFlags;
}
public void EndBufferUpdate(uint cookie)
{
// null in unit tests
_debuggerTextLinesOpt?.SetStateFlags(cookie);
}
public ITextCaret Caret
{
get { return _innerTextView.Caret; }
}
public bool HasAggregateFocus
{
get { return _innerTextView.HasAggregateFocus; }
}
public bool InLayout
{
get { return _innerTextView.InLayout; }
}
public bool IsClosed
{
get { return _innerTextView.IsClosed; }
}
public bool IsMouseOverViewOrAdornments
{
get { return _innerTextView.IsMouseOverViewOrAdornments; }
}
public double LineHeight
{
get { return _innerTextView.LineHeight; }
}
public double MaxTextRightCoordinate
{
get { return _innerTextView.MaxTextRightCoordinate; }
}
public IEditorOptions Options
{
get { return _innerTextView.Options; }
}
public PropertyCollection Properties
{
get { return _innerTextView.Properties; }
}
public ITrackingSpan ProvisionalTextHighlight
{
get
{
return _innerTextView.ProvisionalTextHighlight;
}
set
{
_innerTextView.ProvisionalTextHighlight = value;
}
}
public ITextViewRoleSet Roles
{
get { return _innerTextView.Roles; }
}
public ITextSelection Selection
{
get { return _innerTextView.Selection; }
}
public ITextViewLineCollection TextViewLines
{
get { return _innerTextView.TextViewLines; }
}
public ITextViewModel TextViewModel
{
get { return _innerTextView.TextViewModel; }
}
public IViewScroller ViewScroller
{
get { return _innerTextView.ViewScroller; }
}
public double ViewportBottom
{
get { return _innerTextView.ViewportBottom; }
}
public double ViewportHeight
{
get { return _innerTextView.ViewportHeight; }
}
public double ViewportLeft
{
get
{
return _innerTextView.ViewportLeft;
}
set
{
_innerTextView.ViewportLeft = value;
}
}
public double ViewportRight
{
get { return _innerTextView.ViewportRight; }
}
public double ViewportTop
{
get { return _innerTextView.ViewportTop; }
}
public double ViewportWidth
{
get { return _innerTextView.ViewportWidth; }
}
public ITextSnapshot VisualSnapshot
{
get { return _innerTextView.VisualSnapshot; }
}
public ITextDataModel TextDataModel
{
get { return _innerTextView.TextDataModel; }
}
public ITextBuffer TextBuffer
{
get
{
return _innerTextView.TextBuffer;
}
}
public ITextSnapshot TextSnapshot
{
get
{
return _innerTextView.TextSnapshot;
}
}
public FrameworkElement VisualElement
{
get
{
return _innerTextView.VisualElement;
}
}
public Brush Background
{
get
{
return _innerTextView.Background;
}
set
{
_innerTextView.Background = value;
}
}
IWpfTextViewLineCollection IWpfTextView.TextViewLines
{
get
{
return _innerTextView.TextViewLines;
}
}
public IFormattedLineSource FormattedLineSource
{
get
{
return _innerTextView.FormattedLineSource;
}
}
public ILineTransformSource LineTransformSource
{
get
{
return _innerTextView.LineTransformSource;
}
}
public double ZoomLevel
{
get
{
return _innerTextView.ZoomLevel;
}
set
{
_innerTextView.ZoomLevel = value;
}
}
public bool InOuterLayout => throw new NotImplementedException();
public IMultiSelectionBroker MultiSelectionBroker
{
get
{
if (_multiSelectionBroker == null)
{
_multiSelectionBroker = _innerTextView.GetMultiSelectionBroker();
}
return _multiSelectionBroker;
}
}
public void Close()
=> throw new NotSupportedException();
public void DisplayTextLineContainingBufferPosition(SnapshotPoint bufferPosition, double verticalDistance, ViewRelativePosition relativeTo, double? viewportWidthOverride, double? viewportHeightOverride)
=> throw new NotSupportedException();
public void DisplayTextLineContainingBufferPosition(SnapshotPoint bufferPosition, double verticalDistance, ViewRelativePosition relativeTo)
=> throw new NotSupportedException();
public SnapshotSpan GetTextElementSpan(SnapshotPoint point)
=> throw new NotSupportedException();
public ITextViewLine GetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition)
=> _innerTextView.GetTextViewLineContainingBufferPosition(bufferPosition);
public void QueueSpaceReservationStackRefresh()
=> throw new NotSupportedException();
public IAdornmentLayer GetAdornmentLayer(string name)
=> _innerTextView.GetAdornmentLayer(name);
public ISpaceReservationManager GetSpaceReservationManager(string name)
=> _innerTextView.GetSpaceReservationManager(name);
IWpfTextViewLine IWpfTextView.GetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition)
=> _innerTextView.GetTextViewLineContainingBufferPosition(bufferPosition);
public void Cleanup()
{
// The innerTextView of the immediate window never closes, but we want
// our completion subscribers to unsubscribe from events when this
// DebuggerTextView is no longer in use.
if (this.IsImmediateWindow)
{
this.ClosedInternal?.Invoke(this, EventArgs.Empty);
}
_innerTextView.Properties.RemoveProperty(CompletionRoot);
}
public void QueuePostLayoutAction(Action action) => _innerTextView.QueuePostLayoutAction(action);
public bool TryGetTextViewLines(out ITextViewLineCollection textViewLines) => _innerTextView.TryGetTextViewLines(out textViewLines);
public bool TryGetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition, out ITextViewLine textViewLine)
=> _innerTextView.TryGetTextViewLineContainingBufferPosition(bufferPosition, out textViewLine);
private event EventHandler ClosedInternal;
#pragma warning disable 67
public event EventHandler MaxTextRightCoordinateChanged;
#pragma warning restore 67
public event EventHandler Closed
{
add
{
if (this.IsImmediateWindow)
{
this.ClosedInternal += value;
}
else
{
_innerTextView.Closed += value;
}
}
remove
{
if (this.IsImmediateWindow)
{
this.ClosedInternal -= value;
}
else
{
_innerTextView.Closed -= value;
}
}
}
public event EventHandler GotAggregateFocus
{
add { _innerTextView.GotAggregateFocus += value; }
remove { _innerTextView.GotAggregateFocus -= value; }
}
public event EventHandler<TextViewLayoutChangedEventArgs> LayoutChanged
{
add { _innerTextView.LayoutChanged += value; }
remove { _innerTextView.LayoutChanged -= value; }
}
public event EventHandler LostAggregateFocus
{
add { _innerTextView.LostAggregateFocus += value; }
remove { _innerTextView.LostAggregateFocus -= value; }
}
public event EventHandler<MouseHoverEventArgs> MouseHover
{
add { _innerTextView.MouseHover += value; }
remove { _innerTextView.MouseHover -= value; }
}
public event EventHandler ViewportHeightChanged
{
add { _innerTextView.ViewportHeightChanged += value; }
remove { _innerTextView.ViewportHeightChanged -= value; }
}
public event EventHandler ViewportLeftChanged
{
add { _innerTextView.ViewportLeftChanged += value; }
remove { _innerTextView.ViewportLeftChanged -= value; }
}
public event EventHandler ViewportWidthChanged
{
add { _innerTextView.ViewportWidthChanged += value; }
remove { _innerTextView.ViewportWidthChanged -= value; }
}
public event EventHandler<BackgroundBrushChangedEventArgs> BackgroundBrushChanged
{
add { _innerTextView.BackgroundBrushChanged += value; }
remove { _innerTextView.BackgroundBrushChanged -= value; }
}
public event EventHandler<ZoomLevelChangedEventArgs> ZoomLevelChanged
{
add { _innerTextView.ZoomLevelChanged += value; }
remove { _innerTextView.ZoomLevelChanged -= 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.
#nullable disable
using System;
using System.Windows;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DebuggerIntelliSense
{
internal partial class DebuggerTextView : IWpfTextView, IDebuggerTextView2, ITextView2
{
/// <summary>
/// The actual debugger view of the watch or immediate window that we're wrapping
/// </summary>
private readonly IWpfTextView _innerTextView;
private readonly IVsTextLines _debuggerTextLinesOpt;
private IMultiSelectionBroker _multiSelectionBroker;
// This name "CompletionRoot" is specified on the Editor side.
// Roslyn must match the name.
// The const should be removed with resolution of https://github.com/dotnet/roslyn/issues/31189
public const string CompletionRoot = nameof(CompletionRoot);
public DebuggerTextView(
IWpfTextView innerTextView,
IBufferGraph bufferGraph,
IVsTextLines debuggerTextLinesOpt,
bool isImmediateWindow)
{
_innerTextView = innerTextView;
_debuggerTextLinesOpt = debuggerTextLinesOpt;
BufferGraph = bufferGraph;
IsImmediateWindow = isImmediateWindow;
// The editor requires the current top buffer.
// TODO it seems to be a hack. It should be removed.
// Here is an issue to track: https://github.com/dotnet/roslyn/issues/31189
// Starting debugging for the second time, we already have the property set.
_innerTextView.Properties[CompletionRoot] = bufferGraph.TopBuffer;
}
/// <summary>
/// We basically replace the innerTextView's BufferGraph with our own custom projection graph
/// that projects the immediate window contents into a context buffer:
///
/// (1)
/// (2) (5)
/// (3) (6)
/// (4)
/// (1) Top level projection buffer - the subject buffer used by intellisense
/// (2/3) Currently a double projection buffer combo that elides away the ? in the immediate window, and may add some
/// boilerplate code to force an expression context.
/// (4) innerTextView.TextBuffer, what the user actually sees in the watch/immediate windows
/// (5) A read-only projection of (6)
/// (6) The context buffer which is typically a source file
///
/// </summary>
public IBufferGraph BufferGraph
{
get;
}
public bool IsImmediateWindow
{
get;
}
public uint StartBufferUpdate()
{
// null in unit tests
if (_debuggerTextLinesOpt == null)
{
return 0;
}
_debuggerTextLinesOpt.GetStateFlags(out var bufferFlags);
_debuggerTextLinesOpt.SetStateFlags((uint)((BUFFERSTATEFLAGS)bufferFlags & ~BUFFERSTATEFLAGS.BSF_USER_READONLY));
return bufferFlags;
}
public void EndBufferUpdate(uint cookie)
{
// null in unit tests
_debuggerTextLinesOpt?.SetStateFlags(cookie);
}
public ITextCaret Caret
{
get { return _innerTextView.Caret; }
}
public bool HasAggregateFocus
{
get { return _innerTextView.HasAggregateFocus; }
}
public bool InLayout
{
get { return _innerTextView.InLayout; }
}
public bool IsClosed
{
get { return _innerTextView.IsClosed; }
}
public bool IsMouseOverViewOrAdornments
{
get { return _innerTextView.IsMouseOverViewOrAdornments; }
}
public double LineHeight
{
get { return _innerTextView.LineHeight; }
}
public double MaxTextRightCoordinate
{
get { return _innerTextView.MaxTextRightCoordinate; }
}
public IEditorOptions Options
{
get { return _innerTextView.Options; }
}
public PropertyCollection Properties
{
get { return _innerTextView.Properties; }
}
public ITrackingSpan ProvisionalTextHighlight
{
get
{
return _innerTextView.ProvisionalTextHighlight;
}
set
{
_innerTextView.ProvisionalTextHighlight = value;
}
}
public ITextViewRoleSet Roles
{
get { return _innerTextView.Roles; }
}
public ITextSelection Selection
{
get { return _innerTextView.Selection; }
}
public ITextViewLineCollection TextViewLines
{
get { return _innerTextView.TextViewLines; }
}
public ITextViewModel TextViewModel
{
get { return _innerTextView.TextViewModel; }
}
public IViewScroller ViewScroller
{
get { return _innerTextView.ViewScroller; }
}
public double ViewportBottom
{
get { return _innerTextView.ViewportBottom; }
}
public double ViewportHeight
{
get { return _innerTextView.ViewportHeight; }
}
public double ViewportLeft
{
get
{
return _innerTextView.ViewportLeft;
}
set
{
_innerTextView.ViewportLeft = value;
}
}
public double ViewportRight
{
get { return _innerTextView.ViewportRight; }
}
public double ViewportTop
{
get { return _innerTextView.ViewportTop; }
}
public double ViewportWidth
{
get { return _innerTextView.ViewportWidth; }
}
public ITextSnapshot VisualSnapshot
{
get { return _innerTextView.VisualSnapshot; }
}
public ITextDataModel TextDataModel
{
get { return _innerTextView.TextDataModel; }
}
public ITextBuffer TextBuffer
{
get
{
return _innerTextView.TextBuffer;
}
}
public ITextSnapshot TextSnapshot
{
get
{
return _innerTextView.TextSnapshot;
}
}
public FrameworkElement VisualElement
{
get
{
return _innerTextView.VisualElement;
}
}
public Brush Background
{
get
{
return _innerTextView.Background;
}
set
{
_innerTextView.Background = value;
}
}
IWpfTextViewLineCollection IWpfTextView.TextViewLines
{
get
{
return _innerTextView.TextViewLines;
}
}
public IFormattedLineSource FormattedLineSource
{
get
{
return _innerTextView.FormattedLineSource;
}
}
public ILineTransformSource LineTransformSource
{
get
{
return _innerTextView.LineTransformSource;
}
}
public double ZoomLevel
{
get
{
return _innerTextView.ZoomLevel;
}
set
{
_innerTextView.ZoomLevel = value;
}
}
public bool InOuterLayout => throw new NotImplementedException();
public IMultiSelectionBroker MultiSelectionBroker
{
get
{
if (_multiSelectionBroker == null)
{
_multiSelectionBroker = _innerTextView.GetMultiSelectionBroker();
}
return _multiSelectionBroker;
}
}
public void Close()
=> throw new NotSupportedException();
public void DisplayTextLineContainingBufferPosition(SnapshotPoint bufferPosition, double verticalDistance, ViewRelativePosition relativeTo, double? viewportWidthOverride, double? viewportHeightOverride)
=> throw new NotSupportedException();
public void DisplayTextLineContainingBufferPosition(SnapshotPoint bufferPosition, double verticalDistance, ViewRelativePosition relativeTo)
=> throw new NotSupportedException();
public SnapshotSpan GetTextElementSpan(SnapshotPoint point)
=> throw new NotSupportedException();
public ITextViewLine GetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition)
=> _innerTextView.GetTextViewLineContainingBufferPosition(bufferPosition);
public void QueueSpaceReservationStackRefresh()
=> throw new NotSupportedException();
public IAdornmentLayer GetAdornmentLayer(string name)
=> _innerTextView.GetAdornmentLayer(name);
public ISpaceReservationManager GetSpaceReservationManager(string name)
=> _innerTextView.GetSpaceReservationManager(name);
IWpfTextViewLine IWpfTextView.GetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition)
=> _innerTextView.GetTextViewLineContainingBufferPosition(bufferPosition);
public void Cleanup()
{
// The innerTextView of the immediate window never closes, but we want
// our completion subscribers to unsubscribe from events when this
// DebuggerTextView is no longer in use.
if (this.IsImmediateWindow)
{
this.ClosedInternal?.Invoke(this, EventArgs.Empty);
}
_innerTextView.Properties.RemoveProperty(CompletionRoot);
}
public void QueuePostLayoutAction(Action action) => _innerTextView.QueuePostLayoutAction(action);
public bool TryGetTextViewLines(out ITextViewLineCollection textViewLines) => _innerTextView.TryGetTextViewLines(out textViewLines);
public bool TryGetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition, out ITextViewLine textViewLine)
=> _innerTextView.TryGetTextViewLineContainingBufferPosition(bufferPosition, out textViewLine);
private event EventHandler ClosedInternal;
#pragma warning disable 67
public event EventHandler MaxTextRightCoordinateChanged;
#pragma warning restore 67
public event EventHandler Closed
{
add
{
if (this.IsImmediateWindow)
{
this.ClosedInternal += value;
}
else
{
_innerTextView.Closed += value;
}
}
remove
{
if (this.IsImmediateWindow)
{
this.ClosedInternal -= value;
}
else
{
_innerTextView.Closed -= value;
}
}
}
public event EventHandler GotAggregateFocus
{
add { _innerTextView.GotAggregateFocus += value; }
remove { _innerTextView.GotAggregateFocus -= value; }
}
public event EventHandler<TextViewLayoutChangedEventArgs> LayoutChanged
{
add { _innerTextView.LayoutChanged += value; }
remove { _innerTextView.LayoutChanged -= value; }
}
public event EventHandler LostAggregateFocus
{
add { _innerTextView.LostAggregateFocus += value; }
remove { _innerTextView.LostAggregateFocus -= value; }
}
public event EventHandler<MouseHoverEventArgs> MouseHover
{
add { _innerTextView.MouseHover += value; }
remove { _innerTextView.MouseHover -= value; }
}
public event EventHandler ViewportHeightChanged
{
add { _innerTextView.ViewportHeightChanged += value; }
remove { _innerTextView.ViewportHeightChanged -= value; }
}
public event EventHandler ViewportLeftChanged
{
add { _innerTextView.ViewportLeftChanged += value; }
remove { _innerTextView.ViewportLeftChanged -= value; }
}
public event EventHandler ViewportWidthChanged
{
add { _innerTextView.ViewportWidthChanged += value; }
remove { _innerTextView.ViewportWidthChanged -= value; }
}
public event EventHandler<BackgroundBrushChangedEventArgs> BackgroundBrushChanged
{
add { _innerTextView.BackgroundBrushChanged += value; }
remove { _innerTextView.BackgroundBrushChanged -= value; }
}
public event EventHandler<ZoomLevelChangedEventArgs> ZoomLevelChanged
{
add { _innerTextView.ZoomLevelChanged += value; }
remove { _innerTextView.ZoomLevelChanged -= value; }
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core.Wpf/ExternalAccess/VSTypeScript/VSTypeScriptSignatureHelpClassifierProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[Export(typeof(IVSTypeScriptSignatureHelpClassifierProvider))]
[Shared]
internal sealed class VSTypeScriptSignatureHelpClassifierProvider
: IVSTypeScriptSignatureHelpClassifierProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VSTypeScriptSignatureHelpClassifierProvider()
{
}
public IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap)
=> new SignatureHelpClassifier(textBuffer, typeMap);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[Export(typeof(IVSTypeScriptSignatureHelpClassifierProvider))]
[Shared]
internal sealed class VSTypeScriptSignatureHelpClassifierProvider
: IVSTypeScriptSignatureHelpClassifierProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VSTypeScriptSignatureHelpClassifierProvider()
{
}
public IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap)
=> new SignatureHelpClassifier(textBuffer, typeMap);
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Binder/InContainerBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A binder that places the members of a symbol in scope.
/// </summary>
internal class InContainerBinder : Binder
{
private readonly NamespaceOrTypeSymbol _container;
/// <summary>
/// Creates a binder for a container.
/// </summary>
internal InContainerBinder(NamespaceOrTypeSymbol container, Binder next)
: base(next)
{
Debug.Assert((object)container != null);
_container = container;
}
internal NamespaceOrTypeSymbol Container
{
get
{
return _container;
}
}
internal override Symbol ContainingMemberOrLambda
{
get
{
var merged = _container as MergedNamespaceSymbol;
return ((object)merged != null) ? merged.GetConstituentForCompilation(this.Compilation) : _container;
}
}
private bool IsScriptClass
{
get { return (_container.Kind == SymbolKind.NamedType) && ((NamedTypeSymbol)_container).IsScriptClass; }
}
internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved)
{
var type = _container as NamedTypeSymbol;
if ((object)type != null)
{
return this.IsSymbolAccessibleConditional(symbol, type, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo);
}
else
{
return Next.IsAccessibleHelper(symbol, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); // delegate to containing Binder, eventually checking assembly.
}
}
internal override bool SupportsExtensionMethods
{
get { return true; }
}
internal override void GetCandidateExtensionMethods(
ArrayBuilder<MethodSymbol> methods,
string name,
int arity,
LookupOptions options,
Binder originalBinder)
{
if (_container.Kind == SymbolKind.Namespace)
{
((NamespaceSymbol)_container).GetExtensionMethods(methods, name, arity, options);
}
}
internal override TypeWithAnnotations GetIteratorElementType()
{
if (IsScriptClass)
{
// This is the scenario where a `yield return` exists in the script file as a global statement.
// This method is to guard against hitting `BuckStopsHereBinder` and crash.
return TypeWithAnnotations.Create(this.Compilation.GetSpecialType(SpecialType.System_Object));
}
else
{
// This path would eventually throw, if we didn't have the case above.
return Next.GetIteratorElementType();
}
}
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);
// first lookup members of the namespace
if ((options & LookupOptions.NamespaceAliasesOnly) == 0)
{
this.LookupMembersInternal(result, _container, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo);
if (result.IsMultiViable)
{
if (arity == 0)
{
// symbols cannot conflict with using alias names
if (Next is WithExternAndUsingAliasesBinder withUsingAliases && withUsingAliases.IsUsingAlias(name, originalBinder.IsSemanticModelBinder, basesBeingResolved))
{
CSDiagnosticInfo diagInfo = new CSDiagnosticInfo(ErrorCode.ERR_ConflictAliasAndMember, name, _container);
var error = new ExtendedErrorTypeSymbol((NamespaceOrTypeSymbol)null, name, arity, diagInfo, unreported: true);
result.SetFrom(LookupResult.Good(error)); // force lookup to be done w/ error symbol as result
}
}
return;
}
}
}
protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder)
{
this.AddMemberLookupSymbolsInfo(result, _container, options, originalBinder);
}
protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken)
{
return null;
}
protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken)
{
return null;
}
internal override uint LocalScopeDepth => Binder.ExternalScope;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A binder that places the members of a symbol in scope.
/// </summary>
internal class InContainerBinder : Binder
{
private readonly NamespaceOrTypeSymbol _container;
/// <summary>
/// Creates a binder for a container.
/// </summary>
internal InContainerBinder(NamespaceOrTypeSymbol container, Binder next)
: base(next)
{
Debug.Assert((object)container != null);
_container = container;
}
internal NamespaceOrTypeSymbol Container
{
get
{
return _container;
}
}
internal override Symbol ContainingMemberOrLambda
{
get
{
var merged = _container as MergedNamespaceSymbol;
return ((object)merged != null) ? merged.GetConstituentForCompilation(this.Compilation) : _container;
}
}
private bool IsScriptClass
{
get { return (_container.Kind == SymbolKind.NamedType) && ((NamedTypeSymbol)_container).IsScriptClass; }
}
internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved)
{
var type = _container as NamedTypeSymbol;
if ((object)type != null)
{
return this.IsSymbolAccessibleConditional(symbol, type, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo);
}
else
{
return Next.IsAccessibleHelper(symbol, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); // delegate to containing Binder, eventually checking assembly.
}
}
internal override bool SupportsExtensionMethods
{
get { return true; }
}
internal override void GetCandidateExtensionMethods(
ArrayBuilder<MethodSymbol> methods,
string name,
int arity,
LookupOptions options,
Binder originalBinder)
{
if (_container.Kind == SymbolKind.Namespace)
{
((NamespaceSymbol)_container).GetExtensionMethods(methods, name, arity, options);
}
}
internal override TypeWithAnnotations GetIteratorElementType()
{
if (IsScriptClass)
{
// This is the scenario where a `yield return` exists in the script file as a global statement.
// This method is to guard against hitting `BuckStopsHereBinder` and crash.
return TypeWithAnnotations.Create(this.Compilation.GetSpecialType(SpecialType.System_Object));
}
else
{
// This path would eventually throw, if we didn't have the case above.
return Next.GetIteratorElementType();
}
}
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);
// first lookup members of the namespace
if ((options & LookupOptions.NamespaceAliasesOnly) == 0)
{
this.LookupMembersInternal(result, _container, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo);
if (result.IsMultiViable)
{
if (arity == 0)
{
// symbols cannot conflict with using alias names
if (Next is WithExternAndUsingAliasesBinder withUsingAliases && withUsingAliases.IsUsingAlias(name, originalBinder.IsSemanticModelBinder, basesBeingResolved))
{
CSDiagnosticInfo diagInfo = new CSDiagnosticInfo(ErrorCode.ERR_ConflictAliasAndMember, name, _container);
var error = new ExtendedErrorTypeSymbol((NamespaceOrTypeSymbol)null, name, arity, diagInfo, unreported: true);
result.SetFrom(LookupResult.Good(error)); // force lookup to be done w/ error symbol as result
}
}
return;
}
}
}
protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder)
{
this.AddMemberLookupSymbolsInfo(result, _container, options, originalBinder);
}
protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken)
{
return null;
}
protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken)
{
return null;
}
internal override uint LocalScopeDepth => Binder.ExternalScope;
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/InheritanceMargin/SerializableInheritanceMarginItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.InheritanceMargin
{
[DataContract]
internal readonly struct SerializableInheritanceMarginItem
{
[DataMember(Order = 0)]
public readonly int LineNumber;
[DataMember(Order = 1)]
public readonly ImmutableArray<TaggedText> DisplayTexts;
[DataMember(Order = 2)]
public readonly Glyph Glyph;
[DataMember(Order = 3)]
public readonly ImmutableArray<SerializableInheritanceTargetItem> TargetItems;
public SerializableInheritanceMarginItem(int lineNumber, ImmutableArray<TaggedText> displayTexts, Glyph glyph, ImmutableArray<SerializableInheritanceTargetItem> targetItems)
{
LineNumber = lineNumber;
DisplayTexts = displayTexts;
Glyph = glyph;
TargetItems = targetItems;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.InheritanceMargin
{
[DataContract]
internal readonly struct SerializableInheritanceMarginItem
{
[DataMember(Order = 0)]
public readonly int LineNumber;
[DataMember(Order = 1)]
public readonly ImmutableArray<TaggedText> DisplayTexts;
[DataMember(Order = 2)]
public readonly Glyph Glyph;
[DataMember(Order = 3)]
public readonly ImmutableArray<SerializableInheritanceTargetItem> TargetItems;
public SerializableInheritanceMarginItem(int lineNumber, ImmutableArray<TaggedText> displayTexts, Glyph glyph, ImmutableArray<SerializableInheritanceTargetItem> targetItems)
{
LineNumber = lineNumber;
DisplayTexts = displayTexts;
Glyph = glyph;
TargetItems = targetItems;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/MetadataDecoder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE
{
/// <summary>
/// Helper class to resolve metadata tokens and signatures.
/// </summary>
internal class MetadataDecoder : MetadataDecoder<PEModuleSymbol, TypeSymbol, MethodSymbol, FieldSymbol, Symbol>
{
/// <summary>
/// Type context for resolving generic type arguments.
/// </summary>
private readonly PENamedTypeSymbol _typeContextOpt;
/// <summary>
/// Method context for resolving generic method type arguments.
/// </summary>
private readonly PEMethodSymbol _methodContextOpt;
public MetadataDecoder(
PEModuleSymbol moduleSymbol,
PENamedTypeSymbol context) :
this(moduleSymbol, context, null)
{
}
public MetadataDecoder(
PEModuleSymbol moduleSymbol,
PEMethodSymbol context) :
this(moduleSymbol, (PENamedTypeSymbol)context.ContainingType, context)
{
}
public MetadataDecoder(
PEModuleSymbol moduleSymbol) :
this(moduleSymbol, null, null)
{
}
private MetadataDecoder(PEModuleSymbol moduleSymbol, PENamedTypeSymbol typeContextOpt, PEMethodSymbol methodContextOpt)
// TODO (tomat): if the containing assembly is a source assembly and we are about to decode assembly level attributes, we run into a cycle,
// so for now ignore the assembly identity.
: base(moduleSymbol.Module, (moduleSymbol.ContainingAssembly is PEAssemblySymbol) ? moduleSymbol.ContainingAssembly.Identity : null, SymbolFactory.Instance, moduleSymbol)
{
Debug.Assert((object)moduleSymbol != null);
_typeContextOpt = typeContextOpt;
_methodContextOpt = methodContextOpt;
}
internal PEModuleSymbol ModuleSymbol
{
get { return moduleSymbol; }
}
protected override TypeSymbol GetGenericMethodTypeParamSymbol(int position)
{
if ((object)_methodContextOpt == null)
{
return new UnsupportedMetadataTypeSymbol(); // type parameter not associated with a method
}
var typeParameters = _methodContextOpt.TypeParameters;
if (typeParameters.Length <= position)
{
return new UnsupportedMetadataTypeSymbol(); // type parameter position too large
}
return typeParameters[position];
}
protected override TypeSymbol GetGenericTypeParamSymbol(int position)
{
PENamedTypeSymbol type = _typeContextOpt;
while ((object)type != null && (type.MetadataArity - type.Arity) > position)
{
type = type.ContainingSymbol as PENamedTypeSymbol;
}
if ((object)type == null || type.MetadataArity <= position)
{
return new UnsupportedMetadataTypeSymbol(); // position of type parameter too large
}
position -= type.MetadataArity - type.Arity;
Debug.Assert(position >= 0 && position < type.Arity);
return type.TypeParameters[position];
}
protected override ConcurrentDictionary<TypeDefinitionHandle, TypeSymbol> GetTypeHandleToTypeMap()
{
return moduleSymbol.TypeHandleToTypeMap;
}
protected override ConcurrentDictionary<TypeReferenceHandle, TypeSymbol> GetTypeRefHandleToTypeMap()
{
return moduleSymbol.TypeRefHandleToTypeMap;
}
protected override TypeSymbol LookupNestedTypeDefSymbol(TypeSymbol container, ref MetadataTypeName emittedName)
{
var result = container.LookupMetadataType(ref emittedName);
Debug.Assert((object)result != null);
return result;
}
/// <summary>
/// Lookup a type defined in referenced assembly.
/// </summary>
/// <param name="referencedAssemblyIndex"></param>
/// <param name="emittedName"></param>
protected override TypeSymbol LookupTopLevelTypeDefSymbol(
int referencedAssemblyIndex,
ref MetadataTypeName emittedName)
{
var assembly = moduleSymbol.GetReferencedAssemblySymbol(referencedAssemblyIndex);
if ((object)assembly == null)
{
return new UnsupportedMetadataTypeSymbol();
}
try
{
return assembly.LookupTopLevelMetadataType(ref emittedName, digThroughForwardedTypes: true);
}
catch (Exception e) when (FatalError.ReportAndPropagate(e)) // Trying to get more useful Watson dumps.
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Lookup a type defined in a module of a multi-module assembly.
/// </summary>
protected override TypeSymbol LookupTopLevelTypeDefSymbol(string moduleName, ref MetadataTypeName emittedName, out bool isNoPiaLocalType)
{
foreach (ModuleSymbol m in moduleSymbol.ContainingAssembly.Modules)
{
if (string.Equals(m.Name, moduleName, StringComparison.OrdinalIgnoreCase))
{
if ((object)m == (object)moduleSymbol)
{
return moduleSymbol.LookupTopLevelMetadataType(ref emittedName, out isNoPiaLocalType);
}
else
{
isNoPiaLocalType = false;
return m.LookupTopLevelMetadataType(ref emittedName);
}
}
}
isNoPiaLocalType = false;
return new MissingMetadataTypeSymbol.TopLevel(new MissingModuleSymbolWithName(moduleSymbol.ContainingAssembly, moduleName), ref emittedName, SpecialType.None);
}
/// <summary>
/// Lookup a type defined in this module.
/// This method will be called only if the type we are
/// looking for hasn't been loaded yet. Otherwise, MetadataDecoder
/// would have found the type in TypeDefRowIdToTypeMap based on its
/// TypeDef row id.
/// </summary>
protected override TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, out bool isNoPiaLocalType)
{
return moduleSymbol.LookupTopLevelMetadataType(ref emittedName, out isNoPiaLocalType);
}
protected override int GetIndexOfReferencedAssembly(AssemblyIdentity identity)
{
// Go through all assemblies referenced by the current module and
// find the one which *exactly* matches the given identity.
// No unification will be performed
var assemblies = this.moduleSymbol.GetReferencedAssemblies();
for (int i = 0; i < assemblies.Length; i++)
{
if (identity.Equals(assemblies[i]))
{
return i;
}
}
return -1;
}
/// <summary>
/// Perform a check whether the type or at least one of its generic arguments
/// is defined in the specified assemblies. The check is performed recursively.
/// </summary>
public static bool IsOrClosedOverATypeFromAssemblies(TypeSymbol symbol, ImmutableArray<AssemblySymbol> assemblies)
{
switch (symbol.Kind)
{
case SymbolKind.TypeParameter:
return false;
case SymbolKind.ArrayType:
return IsOrClosedOverATypeFromAssemblies(((ArrayTypeSymbol)symbol).ElementType, assemblies);
case SymbolKind.PointerType:
return IsOrClosedOverATypeFromAssemblies(((PointerTypeSymbol)symbol).PointedAtType, assemblies);
case SymbolKind.DynamicType:
return false;
case SymbolKind.ErrorType:
goto case SymbolKind.NamedType;
case SymbolKind.NamedType:
var namedType = (NamedTypeSymbol)symbol;
AssemblySymbol containingAssembly = symbol.OriginalDefinition.ContainingAssembly;
int i;
if ((object)containingAssembly != null)
{
for (i = 0; i < assemblies.Length; i++)
{
if (ReferenceEquals(containingAssembly, assemblies[i]))
{
return true;
}
}
}
do
{
var arguments = namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics;
int count = arguments.Length;
for (i = 0; i < count; i++)
{
if (IsOrClosedOverATypeFromAssemblies(arguments[i].Type, assemblies))
{
return true;
}
}
namedType = namedType.ContainingType;
}
while ((object)namedType != null);
return false;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
protected override TypeSymbol SubstituteNoPiaLocalType(
TypeDefinitionHandle typeDef,
ref MetadataTypeName name,
string interfaceGuid,
string scope,
string identifier)
{
TypeSymbol result;
try
{
bool isInterface = Module.IsInterfaceOrThrow(typeDef);
TypeSymbol baseType = null;
if (!isInterface)
{
EntityHandle baseToken = Module.GetBaseTypeOfTypeOrThrow(typeDef);
if (!baseToken.IsNil)
{
baseType = GetTypeOfToken(baseToken);
}
}
result = SubstituteNoPiaLocalType(
ref name,
isInterface,
baseType,
interfaceGuid,
scope,
identifier,
moduleSymbol.ContainingAssembly);
}
catch (BadImageFormatException mrEx)
{
result = GetUnsupportedMetadataTypeSymbol(mrEx);
}
Debug.Assert((object)result != null);
ConcurrentDictionary<TypeDefinitionHandle, TypeSymbol> cache = GetTypeHandleToTypeMap();
Debug.Assert(cache != null);
TypeSymbol newresult = cache.GetOrAdd(typeDef, result);
Debug.Assert(ReferenceEquals(newresult, result) || (newresult.Kind == SymbolKind.ErrorType));
return newresult;
}
/// <summary>
/// Find canonical type for NoPia embedded type.
/// </summary>
/// <returns>
/// Symbol for the canonical type or an ErrorTypeSymbol. Never returns null.
/// </returns>
internal static NamedTypeSymbol SubstituteNoPiaLocalType(
ref MetadataTypeName name,
bool isInterface,
TypeSymbol baseType,
string interfaceGuid,
string scope,
string identifier,
AssemblySymbol referringAssembly)
{
NamedTypeSymbol result = null;
Guid interfaceGuidValue = new Guid();
bool haveInterfaceGuidValue = false;
Guid scopeGuidValue = new Guid();
bool haveScopeGuidValue = false;
if (isInterface && interfaceGuid != null)
{
haveInterfaceGuidValue = Guid.TryParse(interfaceGuid, out interfaceGuidValue);
if (haveInterfaceGuidValue)
{
// To have consistent errors.
scope = null;
identifier = null;
}
}
if (scope != null)
{
haveScopeGuidValue = Guid.TryParse(scope, out scopeGuidValue);
}
foreach (AssemblySymbol assembly in referringAssembly.GetNoPiaResolutionAssemblies())
{
Debug.Assert((object)assembly != null);
if (ReferenceEquals(assembly, referringAssembly))
{
continue;
}
NamedTypeSymbol candidate = assembly.LookupTopLevelMetadataType(ref name, digThroughForwardedTypes: false);
Debug.Assert(!candidate.IsGenericType);
// Ignore type forwarders, error symbols and non-public types
if (candidate.Kind == SymbolKind.ErrorType ||
!ReferenceEquals(candidate.ContainingAssembly, assembly) ||
candidate.DeclaredAccessibility != Accessibility.Public)
{
continue;
}
// Ignore NoPia local types.
// If candidate is coming from metadata, we don't need to do any special check,
// because we do not create symbols for local types. However, local types defined in source
// is another story. However, if compilation explicitly defines a local type, it should be
// represented by a retargeting assembly, which is supposed to hide the local type.
Debug.Assert(!(assembly is SourceAssemblySymbol) || !((SourceAssemblySymbol)assembly).SourceModule.MightContainNoPiaLocalTypes());
string candidateGuid;
bool haveCandidateGuidValue = false;
Guid candidateGuidValue = new Guid();
// The type must be of the same kind (interface, struct, delegate or enum).
switch (candidate.TypeKind)
{
case TypeKind.Interface:
if (!isInterface)
{
continue;
}
// Get candidate's Guid
if (candidate.GetGuidString(out candidateGuid) && candidateGuid != null)
{
haveCandidateGuidValue = Guid.TryParse(candidateGuid, out candidateGuidValue);
}
break;
case TypeKind.Delegate:
case TypeKind.Enum:
case TypeKind.Struct:
if (isInterface)
{
continue;
}
// Let's use a trick. To make sure the kind is the same, make sure
// base type is the same.
SpecialType baseSpecialType = (candidate.BaseTypeNoUseSiteDiagnostics?.SpecialType ?? SpecialType.None);
if (baseSpecialType == SpecialType.None || baseSpecialType != (baseType?.SpecialType ?? SpecialType.None))
{
continue;
}
break;
default:
continue;
}
if (haveInterfaceGuidValue || haveCandidateGuidValue)
{
if (!haveInterfaceGuidValue || !haveCandidateGuidValue ||
candidateGuidValue != interfaceGuidValue)
{
continue;
}
}
else
{
if (!haveScopeGuidValue || identifier == null || !identifier.Equals(name.FullName))
{
continue;
}
// Scope guid must match candidate's assembly guid.
haveCandidateGuidValue = false;
if (assembly.GetGuidString(out candidateGuid) && candidateGuid != null)
{
haveCandidateGuidValue = Guid.TryParse(candidateGuid, out candidateGuidValue);
}
if (!haveCandidateGuidValue || scopeGuidValue != candidateGuidValue)
{
continue;
}
}
// OK. It looks like we found canonical type definition.
if ((object)result != null)
{
// Ambiguity
result = new NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, result, candidate);
break;
}
result = candidate;
}
if ((object)result == null)
{
result = new NoPiaMissingCanonicalTypeSymbol(
referringAssembly,
name.FullName,
interfaceGuid,
scope,
identifier);
}
return result;
}
protected override MethodSymbol FindMethodSymbolInType(TypeSymbol typeSymbol, MethodDefinitionHandle targetMethodDef)
{
Debug.Assert(typeSymbol is PENamedTypeSymbol || typeSymbol is ErrorTypeSymbol);
foreach (Symbol member in typeSymbol.GetMembersUnordered())
{
PEMethodSymbol method = member as PEMethodSymbol;
if ((object)method != null && method.Handle == targetMethodDef)
{
return method;
}
}
return null;
}
protected override FieldSymbol FindFieldSymbolInType(TypeSymbol typeSymbol, FieldDefinitionHandle fieldDef)
{
Debug.Assert(typeSymbol is PENamedTypeSymbol || typeSymbol is ErrorTypeSymbol);
foreach (Symbol member in typeSymbol.GetMembersUnordered())
{
PEFieldSymbol field = member as PEFieldSymbol;
if ((object)field != null && field.Handle == fieldDef)
{
return field;
}
}
return null;
}
internal override Symbol GetSymbolForMemberRef(MemberReferenceHandle memberRef, TypeSymbol scope = null, bool methodsOnly = false)
{
TypeSymbol targetTypeSymbol = GetMemberRefTypeSymbol(memberRef);
if (targetTypeSymbol is null)
{
return null;
}
Debug.Assert(!targetTypeSymbol.IsTupleType);
if ((object)scope != null)
{
Debug.Assert(scope.Kind == SymbolKind.NamedType || scope.Kind == SymbolKind.ErrorType);
// We only want to consider members that are at or above "scope" in the type hierarchy.
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
if (!TypeSymbol.Equals(scope, targetTypeSymbol, TypeCompareKind.ConsiderEverything2) &&
!(targetTypeSymbol.IsInterfaceType()
? scope.AllInterfacesNoUseSiteDiagnostics.IndexOf((NamedTypeSymbol)targetTypeSymbol, 0, SymbolEqualityComparer.CLRSignature) != -1
: scope.IsDerivedFrom(targetTypeSymbol, TypeCompareKind.CLRSignatureCompareOptions, useSiteInfo: ref discardedUseSiteInfo)))
{
return null;
}
}
if (!targetTypeSymbol.IsTupleType)
{
targetTypeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(targetTypeSymbol, elementNames: default);
}
// We're going to use a special decoder that can generate usable symbols for type parameters without full context.
// (We're not just using a different type - we're also changing the type context.)
var memberRefDecoder = new MemberRefMetadataDecoder(moduleSymbol, targetTypeSymbol.OriginalDefinition);
var definition = memberRefDecoder.FindMember(memberRef, methodsOnly);
if (definition is not null && !targetTypeSymbol.IsDefinition)
{
return definition.SymbolAsMember((NamedTypeSymbol)targetTypeSymbol);
}
return definition;
}
protected override void EnqueueTypeSymbolInterfacesAndBaseTypes(Queue<TypeDefinitionHandle> typeDefsToSearch, Queue<TypeSymbol> typeSymbolsToSearch, TypeSymbol typeSymbol)
{
foreach (NamedTypeSymbol @interface in typeSymbol.InterfacesNoUseSiteDiagnostics())
{
EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, @interface);
}
EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, typeSymbol.BaseTypeNoUseSiteDiagnostics);
}
protected override void EnqueueTypeSymbol(Queue<TypeDefinitionHandle> typeDefsToSearch, Queue<TypeSymbol> typeSymbolsToSearch, TypeSymbol typeSymbol)
{
if ((object)typeSymbol != null)
{
PENamedTypeSymbol peTypeSymbol = typeSymbol as PENamedTypeSymbol;
if ((object)peTypeSymbol != null && ReferenceEquals(peTypeSymbol.ContainingPEModule, moduleSymbol))
{
typeDefsToSearch.Enqueue(peTypeSymbol.Handle);
}
else
{
typeSymbolsToSearch.Enqueue(typeSymbol);
}
}
}
protected override MethodDefinitionHandle GetMethodHandle(MethodSymbol method)
{
PEMethodSymbol peMethod = method as PEMethodSymbol;
if ((object)peMethod != null && ReferenceEquals(peMethod.ContainingModule, moduleSymbol))
{
return peMethod.Handle;
}
return default(MethodDefinitionHandle);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE
{
/// <summary>
/// Helper class to resolve metadata tokens and signatures.
/// </summary>
internal class MetadataDecoder : MetadataDecoder<PEModuleSymbol, TypeSymbol, MethodSymbol, FieldSymbol, Symbol>
{
/// <summary>
/// Type context for resolving generic type arguments.
/// </summary>
private readonly PENamedTypeSymbol _typeContextOpt;
/// <summary>
/// Method context for resolving generic method type arguments.
/// </summary>
private readonly PEMethodSymbol _methodContextOpt;
public MetadataDecoder(
PEModuleSymbol moduleSymbol,
PENamedTypeSymbol context) :
this(moduleSymbol, context, null)
{
}
public MetadataDecoder(
PEModuleSymbol moduleSymbol,
PEMethodSymbol context) :
this(moduleSymbol, (PENamedTypeSymbol)context.ContainingType, context)
{
}
public MetadataDecoder(
PEModuleSymbol moduleSymbol) :
this(moduleSymbol, null, null)
{
}
private MetadataDecoder(PEModuleSymbol moduleSymbol, PENamedTypeSymbol typeContextOpt, PEMethodSymbol methodContextOpt)
// TODO (tomat): if the containing assembly is a source assembly and we are about to decode assembly level attributes, we run into a cycle,
// so for now ignore the assembly identity.
: base(moduleSymbol.Module, (moduleSymbol.ContainingAssembly is PEAssemblySymbol) ? moduleSymbol.ContainingAssembly.Identity : null, SymbolFactory.Instance, moduleSymbol)
{
Debug.Assert((object)moduleSymbol != null);
_typeContextOpt = typeContextOpt;
_methodContextOpt = methodContextOpt;
}
internal PEModuleSymbol ModuleSymbol
{
get { return moduleSymbol; }
}
protected override TypeSymbol GetGenericMethodTypeParamSymbol(int position)
{
if ((object)_methodContextOpt == null)
{
return new UnsupportedMetadataTypeSymbol(); // type parameter not associated with a method
}
var typeParameters = _methodContextOpt.TypeParameters;
if (typeParameters.Length <= position)
{
return new UnsupportedMetadataTypeSymbol(); // type parameter position too large
}
return typeParameters[position];
}
protected override TypeSymbol GetGenericTypeParamSymbol(int position)
{
PENamedTypeSymbol type = _typeContextOpt;
while ((object)type != null && (type.MetadataArity - type.Arity) > position)
{
type = type.ContainingSymbol as PENamedTypeSymbol;
}
if ((object)type == null || type.MetadataArity <= position)
{
return new UnsupportedMetadataTypeSymbol(); // position of type parameter too large
}
position -= type.MetadataArity - type.Arity;
Debug.Assert(position >= 0 && position < type.Arity);
return type.TypeParameters[position];
}
protected override ConcurrentDictionary<TypeDefinitionHandle, TypeSymbol> GetTypeHandleToTypeMap()
{
return moduleSymbol.TypeHandleToTypeMap;
}
protected override ConcurrentDictionary<TypeReferenceHandle, TypeSymbol> GetTypeRefHandleToTypeMap()
{
return moduleSymbol.TypeRefHandleToTypeMap;
}
protected override TypeSymbol LookupNestedTypeDefSymbol(TypeSymbol container, ref MetadataTypeName emittedName)
{
var result = container.LookupMetadataType(ref emittedName);
Debug.Assert((object)result != null);
return result;
}
/// <summary>
/// Lookup a type defined in referenced assembly.
/// </summary>
/// <param name="referencedAssemblyIndex"></param>
/// <param name="emittedName"></param>
protected override TypeSymbol LookupTopLevelTypeDefSymbol(
int referencedAssemblyIndex,
ref MetadataTypeName emittedName)
{
var assembly = moduleSymbol.GetReferencedAssemblySymbol(referencedAssemblyIndex);
if ((object)assembly == null)
{
return new UnsupportedMetadataTypeSymbol();
}
try
{
return assembly.LookupTopLevelMetadataType(ref emittedName, digThroughForwardedTypes: true);
}
catch (Exception e) when (FatalError.ReportAndPropagate(e)) // Trying to get more useful Watson dumps.
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Lookup a type defined in a module of a multi-module assembly.
/// </summary>
protected override TypeSymbol LookupTopLevelTypeDefSymbol(string moduleName, ref MetadataTypeName emittedName, out bool isNoPiaLocalType)
{
foreach (ModuleSymbol m in moduleSymbol.ContainingAssembly.Modules)
{
if (string.Equals(m.Name, moduleName, StringComparison.OrdinalIgnoreCase))
{
if ((object)m == (object)moduleSymbol)
{
return moduleSymbol.LookupTopLevelMetadataType(ref emittedName, out isNoPiaLocalType);
}
else
{
isNoPiaLocalType = false;
return m.LookupTopLevelMetadataType(ref emittedName);
}
}
}
isNoPiaLocalType = false;
return new MissingMetadataTypeSymbol.TopLevel(new MissingModuleSymbolWithName(moduleSymbol.ContainingAssembly, moduleName), ref emittedName, SpecialType.None);
}
/// <summary>
/// Lookup a type defined in this module.
/// This method will be called only if the type we are
/// looking for hasn't been loaded yet. Otherwise, MetadataDecoder
/// would have found the type in TypeDefRowIdToTypeMap based on its
/// TypeDef row id.
/// </summary>
protected override TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, out bool isNoPiaLocalType)
{
return moduleSymbol.LookupTopLevelMetadataType(ref emittedName, out isNoPiaLocalType);
}
protected override int GetIndexOfReferencedAssembly(AssemblyIdentity identity)
{
// Go through all assemblies referenced by the current module and
// find the one which *exactly* matches the given identity.
// No unification will be performed
var assemblies = this.moduleSymbol.GetReferencedAssemblies();
for (int i = 0; i < assemblies.Length; i++)
{
if (identity.Equals(assemblies[i]))
{
return i;
}
}
return -1;
}
/// <summary>
/// Perform a check whether the type or at least one of its generic arguments
/// is defined in the specified assemblies. The check is performed recursively.
/// </summary>
public static bool IsOrClosedOverATypeFromAssemblies(TypeSymbol symbol, ImmutableArray<AssemblySymbol> assemblies)
{
switch (symbol.Kind)
{
case SymbolKind.TypeParameter:
return false;
case SymbolKind.ArrayType:
return IsOrClosedOverATypeFromAssemblies(((ArrayTypeSymbol)symbol).ElementType, assemblies);
case SymbolKind.PointerType:
return IsOrClosedOverATypeFromAssemblies(((PointerTypeSymbol)symbol).PointedAtType, assemblies);
case SymbolKind.DynamicType:
return false;
case SymbolKind.ErrorType:
goto case SymbolKind.NamedType;
case SymbolKind.NamedType:
var namedType = (NamedTypeSymbol)symbol;
AssemblySymbol containingAssembly = symbol.OriginalDefinition.ContainingAssembly;
int i;
if ((object)containingAssembly != null)
{
for (i = 0; i < assemblies.Length; i++)
{
if (ReferenceEquals(containingAssembly, assemblies[i]))
{
return true;
}
}
}
do
{
var arguments = namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics;
int count = arguments.Length;
for (i = 0; i < count; i++)
{
if (IsOrClosedOverATypeFromAssemblies(arguments[i].Type, assemblies))
{
return true;
}
}
namedType = namedType.ContainingType;
}
while ((object)namedType != null);
return false;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
protected override TypeSymbol SubstituteNoPiaLocalType(
TypeDefinitionHandle typeDef,
ref MetadataTypeName name,
string interfaceGuid,
string scope,
string identifier)
{
TypeSymbol result;
try
{
bool isInterface = Module.IsInterfaceOrThrow(typeDef);
TypeSymbol baseType = null;
if (!isInterface)
{
EntityHandle baseToken = Module.GetBaseTypeOfTypeOrThrow(typeDef);
if (!baseToken.IsNil)
{
baseType = GetTypeOfToken(baseToken);
}
}
result = SubstituteNoPiaLocalType(
ref name,
isInterface,
baseType,
interfaceGuid,
scope,
identifier,
moduleSymbol.ContainingAssembly);
}
catch (BadImageFormatException mrEx)
{
result = GetUnsupportedMetadataTypeSymbol(mrEx);
}
Debug.Assert((object)result != null);
ConcurrentDictionary<TypeDefinitionHandle, TypeSymbol> cache = GetTypeHandleToTypeMap();
Debug.Assert(cache != null);
TypeSymbol newresult = cache.GetOrAdd(typeDef, result);
Debug.Assert(ReferenceEquals(newresult, result) || (newresult.Kind == SymbolKind.ErrorType));
return newresult;
}
/// <summary>
/// Find canonical type for NoPia embedded type.
/// </summary>
/// <returns>
/// Symbol for the canonical type or an ErrorTypeSymbol. Never returns null.
/// </returns>
internal static NamedTypeSymbol SubstituteNoPiaLocalType(
ref MetadataTypeName name,
bool isInterface,
TypeSymbol baseType,
string interfaceGuid,
string scope,
string identifier,
AssemblySymbol referringAssembly)
{
NamedTypeSymbol result = null;
Guid interfaceGuidValue = new Guid();
bool haveInterfaceGuidValue = false;
Guid scopeGuidValue = new Guid();
bool haveScopeGuidValue = false;
if (isInterface && interfaceGuid != null)
{
haveInterfaceGuidValue = Guid.TryParse(interfaceGuid, out interfaceGuidValue);
if (haveInterfaceGuidValue)
{
// To have consistent errors.
scope = null;
identifier = null;
}
}
if (scope != null)
{
haveScopeGuidValue = Guid.TryParse(scope, out scopeGuidValue);
}
foreach (AssemblySymbol assembly in referringAssembly.GetNoPiaResolutionAssemblies())
{
Debug.Assert((object)assembly != null);
if (ReferenceEquals(assembly, referringAssembly))
{
continue;
}
NamedTypeSymbol candidate = assembly.LookupTopLevelMetadataType(ref name, digThroughForwardedTypes: false);
Debug.Assert(!candidate.IsGenericType);
// Ignore type forwarders, error symbols and non-public types
if (candidate.Kind == SymbolKind.ErrorType ||
!ReferenceEquals(candidate.ContainingAssembly, assembly) ||
candidate.DeclaredAccessibility != Accessibility.Public)
{
continue;
}
// Ignore NoPia local types.
// If candidate is coming from metadata, we don't need to do any special check,
// because we do not create symbols for local types. However, local types defined in source
// is another story. However, if compilation explicitly defines a local type, it should be
// represented by a retargeting assembly, which is supposed to hide the local type.
Debug.Assert(!(assembly is SourceAssemblySymbol) || !((SourceAssemblySymbol)assembly).SourceModule.MightContainNoPiaLocalTypes());
string candidateGuid;
bool haveCandidateGuidValue = false;
Guid candidateGuidValue = new Guid();
// The type must be of the same kind (interface, struct, delegate or enum).
switch (candidate.TypeKind)
{
case TypeKind.Interface:
if (!isInterface)
{
continue;
}
// Get candidate's Guid
if (candidate.GetGuidString(out candidateGuid) && candidateGuid != null)
{
haveCandidateGuidValue = Guid.TryParse(candidateGuid, out candidateGuidValue);
}
break;
case TypeKind.Delegate:
case TypeKind.Enum:
case TypeKind.Struct:
if (isInterface)
{
continue;
}
// Let's use a trick. To make sure the kind is the same, make sure
// base type is the same.
SpecialType baseSpecialType = (candidate.BaseTypeNoUseSiteDiagnostics?.SpecialType ?? SpecialType.None);
if (baseSpecialType == SpecialType.None || baseSpecialType != (baseType?.SpecialType ?? SpecialType.None))
{
continue;
}
break;
default:
continue;
}
if (haveInterfaceGuidValue || haveCandidateGuidValue)
{
if (!haveInterfaceGuidValue || !haveCandidateGuidValue ||
candidateGuidValue != interfaceGuidValue)
{
continue;
}
}
else
{
if (!haveScopeGuidValue || identifier == null || !identifier.Equals(name.FullName))
{
continue;
}
// Scope guid must match candidate's assembly guid.
haveCandidateGuidValue = false;
if (assembly.GetGuidString(out candidateGuid) && candidateGuid != null)
{
haveCandidateGuidValue = Guid.TryParse(candidateGuid, out candidateGuidValue);
}
if (!haveCandidateGuidValue || scopeGuidValue != candidateGuidValue)
{
continue;
}
}
// OK. It looks like we found canonical type definition.
if ((object)result != null)
{
// Ambiguity
result = new NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, result, candidate);
break;
}
result = candidate;
}
if ((object)result == null)
{
result = new NoPiaMissingCanonicalTypeSymbol(
referringAssembly,
name.FullName,
interfaceGuid,
scope,
identifier);
}
return result;
}
protected override MethodSymbol FindMethodSymbolInType(TypeSymbol typeSymbol, MethodDefinitionHandle targetMethodDef)
{
Debug.Assert(typeSymbol is PENamedTypeSymbol || typeSymbol is ErrorTypeSymbol);
foreach (Symbol member in typeSymbol.GetMembersUnordered())
{
PEMethodSymbol method = member as PEMethodSymbol;
if ((object)method != null && method.Handle == targetMethodDef)
{
return method;
}
}
return null;
}
protected override FieldSymbol FindFieldSymbolInType(TypeSymbol typeSymbol, FieldDefinitionHandle fieldDef)
{
Debug.Assert(typeSymbol is PENamedTypeSymbol || typeSymbol is ErrorTypeSymbol);
foreach (Symbol member in typeSymbol.GetMembersUnordered())
{
PEFieldSymbol field = member as PEFieldSymbol;
if ((object)field != null && field.Handle == fieldDef)
{
return field;
}
}
return null;
}
internal override Symbol GetSymbolForMemberRef(MemberReferenceHandle memberRef, TypeSymbol scope = null, bool methodsOnly = false)
{
TypeSymbol targetTypeSymbol = GetMemberRefTypeSymbol(memberRef);
if (targetTypeSymbol is null)
{
return null;
}
Debug.Assert(!targetTypeSymbol.IsTupleType);
if ((object)scope != null)
{
Debug.Assert(scope.Kind == SymbolKind.NamedType || scope.Kind == SymbolKind.ErrorType);
// We only want to consider members that are at or above "scope" in the type hierarchy.
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
if (!TypeSymbol.Equals(scope, targetTypeSymbol, TypeCompareKind.ConsiderEverything2) &&
!(targetTypeSymbol.IsInterfaceType()
? scope.AllInterfacesNoUseSiteDiagnostics.IndexOf((NamedTypeSymbol)targetTypeSymbol, 0, SymbolEqualityComparer.CLRSignature) != -1
: scope.IsDerivedFrom(targetTypeSymbol, TypeCompareKind.CLRSignatureCompareOptions, useSiteInfo: ref discardedUseSiteInfo)))
{
return null;
}
}
if (!targetTypeSymbol.IsTupleType)
{
targetTypeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(targetTypeSymbol, elementNames: default);
}
// We're going to use a special decoder that can generate usable symbols for type parameters without full context.
// (We're not just using a different type - we're also changing the type context.)
var memberRefDecoder = new MemberRefMetadataDecoder(moduleSymbol, targetTypeSymbol.OriginalDefinition);
var definition = memberRefDecoder.FindMember(memberRef, methodsOnly);
if (definition is not null && !targetTypeSymbol.IsDefinition)
{
return definition.SymbolAsMember((NamedTypeSymbol)targetTypeSymbol);
}
return definition;
}
protected override void EnqueueTypeSymbolInterfacesAndBaseTypes(Queue<TypeDefinitionHandle> typeDefsToSearch, Queue<TypeSymbol> typeSymbolsToSearch, TypeSymbol typeSymbol)
{
foreach (NamedTypeSymbol @interface in typeSymbol.InterfacesNoUseSiteDiagnostics())
{
EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, @interface);
}
EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, typeSymbol.BaseTypeNoUseSiteDiagnostics);
}
protected override void EnqueueTypeSymbol(Queue<TypeDefinitionHandle> typeDefsToSearch, Queue<TypeSymbol> typeSymbolsToSearch, TypeSymbol typeSymbol)
{
if ((object)typeSymbol != null)
{
PENamedTypeSymbol peTypeSymbol = typeSymbol as PENamedTypeSymbol;
if ((object)peTypeSymbol != null && ReferenceEquals(peTypeSymbol.ContainingPEModule, moduleSymbol))
{
typeDefsToSearch.Enqueue(peTypeSymbol.Handle);
}
else
{
typeSymbolsToSearch.Enqueue(typeSymbol);
}
}
}
protected override MethodDefinitionHandle GetMethodHandle(MethodSymbol method)
{
PEMethodSymbol peMethod = method as PEMethodSymbol;
if ((object)peMethod != null && ReferenceEquals(peMethod.ContainingModule, moduleSymbol))
{
return peMethod.Handle;
}
return default(MethodDefinitionHandle);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest2/Recommendations/GetKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class GetKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int Goo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyAttribute()
{
await VerifyKeywordAsync(
@"class C {
int Goo { [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySet()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySetAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySetAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySetAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlock()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlockAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlockAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlockAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPropertyGetKeyword()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPropertyGetAccessor()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEvent()
{
await VerifyAbsenceAsync(
@"class C {
event Goo E { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexer()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerAttribute()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSet()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlock()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlockAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlockAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlockAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIndexerGetKeyword()
{
await VerifyAbsenceAsync(
@"class C {
int this[int i] { get $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIndexerGetAccessor()
{
await VerifyAbsenceAsync(
@"class C {
int this[int i] { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeSemicolon()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { $$; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtectedInternal()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { protected internal $$ }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternalProtected()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { internal protected $$ }");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class GetKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int Goo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyAttribute()
{
await VerifyKeywordAsync(
@"class C {
int Goo { [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySet()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySetAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySetAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertySetAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set; [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlock()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlockAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlockAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSetAccessorBlockAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int Goo { set { } [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPropertyGetKeyword()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPropertyGetAccessor()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEvent()
{
await VerifyAbsenceAsync(
@"class C {
event Goo E { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexer()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerAttribute()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSet()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set; [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlock()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlockAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlockAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerSetBlockAndAttributeAndPrivate()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { set { } [Bar] private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIndexerGetKeyword()
{
await VerifyAbsenceAsync(
@"class C {
int this[int i] { get $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIndexerGetAccessor()
{
await VerifyAbsenceAsync(
@"class C {
int this[int i] { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeSemicolon()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { $$; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtectedInternal()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { protected internal $$ }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternalProtected()
{
await VerifyKeywordAsync(
@"class C {
int this[int i] { internal protected $$ }");
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Diagnostic/NoLocation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A class that represents no location at all. Useful for errors in command line options, for example.
/// </summary>
/// <remarks></remarks>
internal sealed class NoLocation : Location
{
public static readonly Location Singleton = new NoLocation();
private NoLocation()
{
}
public override LocationKind Kind
{
get { return LocationKind.None; }
}
public override bool Equals(object? obj)
{
return (object)this == obj;
}
public override int GetHashCode()
{
// arbitrary number, since all NoLocation's are equal
return 0x16487756;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A class that represents no location at all. Useful for errors in command line options, for example.
/// </summary>
/// <remarks></remarks>
internal sealed class NoLocation : Location
{
public static readonly Location Singleton = new NoLocation();
private NoLocation()
{
}
public override LocationKind Kind
{
get { return LocationKind.None; }
}
public override bool Equals(object? obj)
{
return (object)this == obj;
}
public override int GetHashCode()
{
// arbitrary number, since all NoLocation's are equal
return 0x16487756;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Analyzers/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConsecutiveBracePlacement
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class ConsecutiveBracePlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public ConsecutiveBracePlacementDiagnosticAnalyzer()
: base(IDEDiagnosticIds.ConsecutiveBracePlacementDiagnosticId,
EnforceOnBuildValues.ConsecutiveBracePlacement,
CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(CSharpAnalyzersResources.Consecutive_braces_must_not_have_a_blank_between_them), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeTree);
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces);
if (option.Value)
return;
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var stack);
Recurse(context, option.Notification.Severity, stack);
}
private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ArrayBuilder<SyntaxNode> stack)
{
var tree = context.Tree;
var cancellationToken = context.CancellationToken;
var root = tree.GetRoot(cancellationToken);
var text = tree.GetText(cancellationToken);
stack.Add(root);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Last();
stack.RemoveLast();
// Don't bother analyzing nodes that have syntax errors in them.
if (current.ContainsDiagnostics && current.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
continue;
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
stack.Add(child.AsNode()!);
else if (child.IsToken)
ProcessToken(context, severity, text, child.AsToken());
}
}
}
private void ProcessToken(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SourceText text, SyntaxToken token)
{
if (!HasExcessBlankLinesAfter(text, token, out var secondBrace, out _))
return;
context.ReportDiagnostic(DiagnosticHelper.Create(
this.Descriptor,
secondBrace.GetLocation(),
severity,
additionalLocations: null,
properties: null));
}
public static bool HasExcessBlankLinesAfter(
SourceText text, SyntaxToken token,
out SyntaxToken secondBrace,
out SyntaxTrivia endOfLineTrivia)
{
secondBrace = default;
endOfLineTrivia = default;
if (!token.IsKind(SyntaxKind.CloseBraceToken))
return false;
var nextToken = token.GetNextToken();
if (!nextToken.IsKind(SyntaxKind.CloseBraceToken))
return false;
var firstBrace = token;
secondBrace = nextToken;
// two } tokens. They need to be on the same line, or if they are not on subsequent lines, then there needs
// to be more than whitespace between them.
var lines = text.Lines;
var firstBraceLine = lines.GetLineFromPosition(firstBrace.SpanStart).LineNumber;
var secondBraceLine = lines.GetLineFromPosition(secondBrace.SpanStart).LineNumber;
var lineCount = secondBraceLine - firstBraceLine;
// if they're both on the same line, or one line apart, then there's no problem.
if (lineCount <= 1)
return false;
// they're multiple lines apart. This i not ok if those lines are all whitespace.
for (var currentLine = firstBraceLine + 1; currentLine < secondBraceLine; currentLine++)
{
if (!IsAllWhitespace(lines[currentLine]))
return false;
}
endOfLineTrivia = secondBrace.LeadingTrivia.Last(t => t.IsKind(SyntaxKind.EndOfLineTrivia));
return endOfLineTrivia != default;
}
private static bool IsAllWhitespace(TextLine textLine)
{
var text = textLine.Text!;
for (var i = textLine.Start; i < textLine.End; i++)
{
if (!SyntaxFacts.IsWhitespace(text[i]))
return false;
}
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.NewLines.ConsecutiveBracePlacement
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class ConsecutiveBracePlacementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public ConsecutiveBracePlacementDiagnosticAnalyzer()
: base(IDEDiagnosticIds.ConsecutiveBracePlacementDiagnosticId,
EnforceOnBuildValues.ConsecutiveBracePlacement,
CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(CSharpAnalyzersResources.Consecutive_braces_must_not_have_a_blank_between_them), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeTree);
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces);
if (option.Value)
return;
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var stack);
Recurse(context, option.Notification.Severity, stack);
}
private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, ArrayBuilder<SyntaxNode> stack)
{
var tree = context.Tree;
var cancellationToken = context.CancellationToken;
var root = tree.GetRoot(cancellationToken);
var text = tree.GetText(cancellationToken);
stack.Add(root);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Last();
stack.RemoveLast();
// Don't bother analyzing nodes that have syntax errors in them.
if (current.ContainsDiagnostics && current.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
continue;
foreach (var child in current.ChildNodesAndTokens())
{
if (child.IsNode)
stack.Add(child.AsNode()!);
else if (child.IsToken)
ProcessToken(context, severity, text, child.AsToken());
}
}
}
private void ProcessToken(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SourceText text, SyntaxToken token)
{
if (!HasExcessBlankLinesAfter(text, token, out var secondBrace, out _))
return;
context.ReportDiagnostic(DiagnosticHelper.Create(
this.Descriptor,
secondBrace.GetLocation(),
severity,
additionalLocations: null,
properties: null));
}
public static bool HasExcessBlankLinesAfter(
SourceText text, SyntaxToken token,
out SyntaxToken secondBrace,
out SyntaxTrivia endOfLineTrivia)
{
secondBrace = default;
endOfLineTrivia = default;
if (!token.IsKind(SyntaxKind.CloseBraceToken))
return false;
var nextToken = token.GetNextToken();
if (!nextToken.IsKind(SyntaxKind.CloseBraceToken))
return false;
var firstBrace = token;
secondBrace = nextToken;
// two } tokens. They need to be on the same line, or if they are not on subsequent lines, then there needs
// to be more than whitespace between them.
var lines = text.Lines;
var firstBraceLine = lines.GetLineFromPosition(firstBrace.SpanStart).LineNumber;
var secondBraceLine = lines.GetLineFromPosition(secondBrace.SpanStart).LineNumber;
var lineCount = secondBraceLine - firstBraceLine;
// if they're both on the same line, or one line apart, then there's no problem.
if (lineCount <= 1)
return false;
// they're multiple lines apart. This i not ok if those lines are all whitespace.
for (var currentLine = firstBraceLine + 1; currentLine < secondBraceLine; currentLine++)
{
if (!IsAllWhitespace(lines[currentLine]))
return false;
}
endOfLineTrivia = secondBrace.LeadingTrivia.Last(t => t.IsKind(SyntaxKind.EndOfLineTrivia));
return endOfLineTrivia != default;
}
private static bool IsAllWhitespace(TextLine textLine)
{
var text = textLine.Text!;
for (var i = textLine.Start; i < textLine.End; i++)
{
if (!SyntaxFacts.IsWhitespace(text[i]))
return false;
}
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Xaml/Impl/Telemetry/IXamlLanguageServerFeedbackService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry
{
/// <summary>
/// Service that collects data for Telemetry in XamlLanguageServer
/// </summary>
internal interface IXamlLanguageServerFeedbackService
{
/// <summary>
/// Create a RequestScope of a request of given documentId
/// </summary>
IRequestScope CreateRequestScope(DocumentId? documentId, string methodName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry
{
/// <summary>
/// Service that collects data for Telemetry in XamlLanguageServer
/// </summary>
internal interface IXamlLanguageServerFeedbackService
{
/// <summary>
/// Create a RequestScope of a request of given documentId
/// </summary>
IRequestScope CreateRequestScope(DocumentId? documentId, string methodName);
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/DocumentSpanExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Navigation;
namespace Microsoft.CodeAnalysis
{
internal static class DocumentSpanExtensions
{
public static bool CanNavigateTo(this DocumentSpan documentSpan, CancellationToken cancellationToken)
{
var workspace = documentSpan.Document.Project.Solution.Workspace;
var service = workspace.Services.GetService<IDocumentNavigationService>();
return service.CanNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan, cancellationToken);
}
public static bool TryNavigateTo(this DocumentSpan documentSpan, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken)
{
var solution = documentSpan.Document.Project.Solution;
var workspace = solution.Workspace;
var service = workspace.Services.GetService<IDocumentNavigationService>();
var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, showInPreviewTab);
options = options.WithChangedOption(NavigationOptions.ActivateTab, activateTab);
return service.TryNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan, options, cancellationToken);
}
public static async Task<bool> IsHiddenAsync(
this DocumentSpan documentSpan, CancellationToken cancellationToken)
{
var document = documentSpan.Document;
if (document.SupportsSyntaxTree)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return tree.IsHiddenPosition(documentSpan.SourceSpan.Start, cancellationToken);
}
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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Navigation;
namespace Microsoft.CodeAnalysis
{
internal static class DocumentSpanExtensions
{
public static bool CanNavigateTo(this DocumentSpan documentSpan, CancellationToken cancellationToken)
{
var workspace = documentSpan.Document.Project.Solution.Workspace;
var service = workspace.Services.GetService<IDocumentNavigationService>();
return service.CanNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan, cancellationToken);
}
public static bool TryNavigateTo(this DocumentSpan documentSpan, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken)
{
var solution = documentSpan.Document.Project.Solution;
var workspace = solution.Workspace;
var service = workspace.Services.GetService<IDocumentNavigationService>();
var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, showInPreviewTab);
options = options.WithChangedOption(NavigationOptions.ActivateTab, activateTab);
return service.TryNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan, options, cancellationToken);
}
public static async Task<bool> IsHiddenAsync(
this DocumentSpan documentSpan, CancellationToken cancellationToken)
{
var document = documentSpan.Document;
if (document.SupportsSyntaxTree)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return tree.IsHiddenPosition(documentSpan.SourceSpan.Start, cancellationToken);
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/AbstractTriviaFormatter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract class AbstractTriviaFormatter
{
#region Caches
private static readonly string[] s_spaceCache;
/// <summary>
/// set up space string caches
/// </summary>
static AbstractTriviaFormatter()
{
s_spaceCache = new string[20];
for (var i = 0; i < 20; i++)
{
s_spaceCache[i] = new string(' ', i);
}
}
#endregion
/// <summary>
/// format the trivia at the line column and put changes to the changes
/// </summary>
private delegate LineColumnDelta Formatter<T>(LineColumn lineColumn, SyntaxTrivia trivia, ArrayBuilder<T> changes, CancellationToken cancellationToken);
/// <summary>
/// create whitespace for the delta at the line column and put changes to the changes
/// </summary>
private delegate void WhitespaceAppender<T>(LineColumn lineColumn, LineColumnDelta delta, TextSpan span, ArrayBuilder<T> changes);
protected readonly FormattingContext Context;
protected readonly ChainedFormattingRules FormattingRules;
protected readonly string OriginalString;
protected readonly int LineBreaks;
protected readonly int Spaces;
protected readonly LineColumn InitialLineColumn;
protected readonly SyntaxToken Token1;
protected readonly SyntaxToken Token2;
private readonly int _indentation;
private readonly bool _firstLineBlank;
public AbstractTriviaFormatter(
FormattingContext context,
ChainedFormattingRules formattingRules,
SyntaxToken token1,
SyntaxToken token2,
string originalString,
int lineBreaks,
int spaces)
{
Contract.ThrowIfNull(context);
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(originalString);
Contract.ThrowIfFalse(lineBreaks >= 0);
Contract.ThrowIfFalse(spaces >= 0);
Contract.ThrowIfTrue(token1 == default && token2 == default);
this.Context = context;
this.FormattingRules = formattingRules;
this.OriginalString = originalString;
this.Token1 = token1;
this.Token2 = token2;
this.LineBreaks = lineBreaks;
this.Spaces = spaces;
this.InitialLineColumn = GetInitialLineColumn();
// "Spaces" holds either space counts between two tokens if two are on same line or indentation of token2 if
// two are on different line. but actual "Indentation" of the line could be different than "Spaces" if there is
// noisy trivia before token2 on the same line.
// this.indentation indicates that trivia's indentation
//
// ex) [indentation]/** */ token2
// [spaces ]
_indentation = (this.LineBreaks > 0) ? GetIndentation() : -1;
// check whether first line between two tokens contains only whitespace
// depends on this we decide where to insert blank lines at the end
_firstLineBlank = FirstLineBlank();
}
/// <summary>
/// return whether this formatting succeeded or not
/// for example, if there is skipped tokens in one of trivia between tokens
/// we consider formatting this region is failed
/// </summary>
protected abstract bool Succeeded();
/// <summary>
/// check whether given trivia is whitespace trivia or not
/// </summary>
protected abstract bool IsWhitespace(SyntaxTrivia trivia);
/// <summary>
/// check whether given trivia is end of line trivia or not
/// </summary>
protected abstract bool IsEndOfLine(SyntaxTrivia trivia);
/// <summary>
/// check whether given string is either null or whitespace
/// </summary>
protected bool IsNullOrWhitespace([NotNullWhen(true)] string? text)
{
if (text == null)
{
return true;
}
for (var i = 0; i < text.Length; i++)
{
if (!IsWhitespace(text[i]) || !IsNewLine(text[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// check whether given char is whitespace
/// </summary>
protected abstract bool IsWhitespace(char ch);
/// <summary>
/// check whether given char is new line char
/// </summary>
protected abstract bool IsNewLine(char ch);
/// <summary>
/// create whitespace trivia
/// </summary>
protected abstract SyntaxTrivia CreateWhitespace(string text);
/// <summary>
/// create end of line trivia
/// </summary>
protected abstract SyntaxTrivia CreateEndOfLine();
/// <summary>
/// return line column rule for the given two trivia
/// </summary>
protected abstract LineColumnRule GetLineColumnRuleBetween(SyntaxTrivia trivia1, LineColumnDelta existingWhitespaceBetween, bool implicitLineBreak, SyntaxTrivia trivia2);
/// <summary>
/// format the given trivia at the line column position and put result to the changes list
/// </summary>
protected abstract LineColumnDelta Format(LineColumn lineColumn, SyntaxTrivia trivia, ArrayBuilder<SyntaxTrivia> changes, CancellationToken cancellationToken);
/// <summary>
/// format the given trivia at the line column position and put text change result to the changes list
/// </summary>
protected abstract LineColumnDelta Format(LineColumn lineColumn, SyntaxTrivia trivia, ArrayBuilder<TextChange> changes, CancellationToken cancellationToken);
/// <summary>
/// returns true if the trivia contains a Line break
/// </summary>
protected abstract bool ContainsImplicitLineBreak(SyntaxTrivia trivia);
protected int StartPosition
{
get
{
if (this.Token1.RawKind == 0)
{
return this.TreeInfo.StartPosition;
}
return this.Token1.Span.End;
}
}
protected int EndPosition
{
get
{
if (this.Token2.RawKind == 0)
{
return this.TreeInfo.EndPosition;
}
return this.Token2.SpanStart;
}
}
protected TreeData TreeInfo
{
get { return this.Context.TreeData; }
}
protected AnalyzerConfigOptions Options
{
get { return this.Context.Options; }
}
protected TokenStream TokenStream
{
get { return this.Context.TokenStream; }
}
public SyntaxTriviaList FormatToSyntaxTrivia(CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var triviaList);
var lineColumn = FormatTrivia(Format, AddWhitespaceTrivia, triviaList, cancellationToken);
// deal with edges
// insert empty linebreaks at the beginning of trivia list
AddExtraLines(lineColumn.Line, triviaList);
if (Succeeded())
{
return new SyntaxTriviaList(triviaList);
}
triviaList.Clear();
AddRange(triviaList, this.Token1.TrailingTrivia);
AddRange(triviaList, this.Token2.LeadingTrivia);
return new SyntaxTriviaList(triviaList);
}
private static void AddRange(ArrayBuilder<SyntaxTrivia> result, SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
result.Add(trivia);
}
public ImmutableArray<TextChange> FormatToTextChanges(CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<TextChange>.GetInstance(out var changes);
var lineColumn = FormatTrivia(Format, AddWhitespaceTextChange, changes, cancellationToken);
// deal with edges
// insert empty linebreaks at the beginning of trivia list
AddExtraLines(lineColumn.Line, changes);
if (Succeeded())
{
return changes.ToImmutable();
}
return ImmutableArray<TextChange>.Empty;
}
private LineColumn FormatTrivia<T>(Formatter<T> formatter, WhitespaceAppender<T> whitespaceAdder, ArrayBuilder<T> changes, CancellationToken cancellationToken)
{
var lineColumn = this.InitialLineColumn;
var existingWhitespaceDelta = LineColumnDelta.Default;
var previousWhitespaceTrivia = default(SyntaxTrivia);
var previousTrivia = default(SyntaxTrivia);
var implicitLineBreak = false;
var list = new TriviaList(this.Token1.TrailingTrivia, this.Token2.LeadingTrivia);
foreach (var trivia in list)
{
if (trivia.RawKind == 0)
{
continue;
}
if (IsWhitespaceOrEndOfLine(trivia))
{
if (IsEndOfLine(trivia))
{
implicitLineBreak = false;
}
existingWhitespaceDelta = existingWhitespaceDelta.With(
GetLineColumnOfWhitespace(
lineColumn,
previousTrivia,
previousWhitespaceTrivia,
existingWhitespaceDelta,
trivia));
previousWhitespaceTrivia = trivia;
continue;
}
previousWhitespaceTrivia = default;
lineColumn = FormatFirstTriviaAndWhitespaceAfter(
lineColumn,
previousTrivia, existingWhitespaceDelta, trivia,
formatter, whitespaceAdder,
changes, implicitLineBreak, cancellationToken);
implicitLineBreak = implicitLineBreak || ContainsImplicitLineBreak(trivia);
existingWhitespaceDelta = LineColumnDelta.Default;
previousTrivia = trivia;
}
lineColumn = FormatFirstTriviaAndWhitespaceAfter(
lineColumn,
previousTrivia, existingWhitespaceDelta, default,
formatter, whitespaceAdder,
changes, implicitLineBreak, cancellationToken);
return lineColumn;
}
private LineColumn FormatFirstTriviaAndWhitespaceAfter<T>(
LineColumn lineColumnBeforeTrivia1,
SyntaxTrivia trivia1,
LineColumnDelta existingWhitespaceBetween,
SyntaxTrivia trivia2,
Formatter<T> format,
WhitespaceAppender<T> addWhitespaceTrivia,
ArrayBuilder<T> changes,
bool implicitLineBreak,
CancellationToken cancellationToken)
{
var lineColumnAfterTrivia1 = trivia1.RawKind == 0 ?
lineColumnBeforeTrivia1 : lineColumnBeforeTrivia1.With(format(lineColumnBeforeTrivia1, trivia1, changes, cancellationToken));
var rule = GetOverallLineColumnRuleBetween(trivia1, existingWhitespaceBetween, implicitLineBreak, trivia2);
var whitespaceDelta = Apply(lineColumnBeforeTrivia1, trivia1, lineColumnAfterTrivia1, existingWhitespaceBetween, trivia2, rule);
var span = GetTextSpan(trivia1, trivia2);
addWhitespaceTrivia(lineColumnAfterTrivia1, whitespaceDelta, span, changes);
return lineColumnAfterTrivia1.With(whitespaceDelta);
}
/// <summary>
/// get line column rule between two trivia
/// </summary>
private LineColumnRule GetOverallLineColumnRuleBetween(SyntaxTrivia trivia1, LineColumnDelta existingWhitespaceBetween, bool implicitLineBreak, SyntaxTrivia trivia2)
{
var defaultRule = GetLineColumnRuleBetween(trivia1, existingWhitespaceBetween, implicitLineBreak, trivia2);
GetTokensAtEdgeOfStructureTrivia(trivia1, trivia2, out var token1, out var token2);
// if there are tokens, try formatting rules to see whether there is a user supplied one
if (token1.RawKind == 0 || token2.RawKind == 0)
{
return defaultRule;
}
// use line defined by the token formatting rules
var lineOperation = this.FormattingRules.GetAdjustNewLinesOperation(token1, token2);
// there is existing lines, but no line operation
if (existingWhitespaceBetween.Lines != 0 && lineOperation == null)
{
return defaultRule;
}
if (lineOperation != null)
{
switch (lineOperation.Option)
{
case AdjustNewLinesOption.PreserveLines:
if (existingWhitespaceBetween.Lines != 0)
{
return defaultRule.With(lines: lineOperation.Line, lineOperation: LineColumnRule.LineOperations.Preserve);
}
break;
case AdjustNewLinesOption.ForceLines:
return defaultRule.With(lines: lineOperation.Line, lineOperation: LineColumnRule.LineOperations.Force);
case AdjustNewLinesOption.ForceLinesIfOnSingleLine:
if (this.Context.TokenStream.TwoTokensOnSameLine(token1, token2))
{
return defaultRule.With(lines: lineOperation.Line, lineOperation: LineColumnRule.LineOperations.Force);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(lineOperation.Option);
}
}
// use space defined by the regular formatting rules
var spaceOperation = this.FormattingRules.GetAdjustSpacesOperation(token1, token2);
if (spaceOperation == null)
{
return defaultRule;
}
if (spaceOperation.Option == AdjustSpacesOption.DefaultSpacesIfOnSingleLine &&
spaceOperation.Space == 1)
{
return defaultRule;
}
return defaultRule.With(spaces: spaceOperation.Space);
}
/// <summary>
/// if the given trivia is the very first or the last trivia between two normal tokens and
/// if the trivia is structured trivia, get one token that belongs to the structured trivia and one belongs to the normal token stream
/// </summary>
private void GetTokensAtEdgeOfStructureTrivia(SyntaxTrivia trivia1, SyntaxTrivia trivia2, out SyntaxToken token1, out SyntaxToken token2)
{
token1 = default;
if (trivia1.RawKind == 0)
{
token1 = this.Token1;
}
else if (trivia1.HasStructure)
{
var lastToken = trivia1.GetStructure()!.GetLastToken(includeZeroWidth: true);
if (ContainsOnlyWhitespace(lastToken.Span.End, lastToken.FullSpan.End))
{
token1 = lastToken;
}
}
token2 = default;
if (trivia2.RawKind == 0)
{
token2 = this.Token2;
}
else if (trivia2.HasStructure)
{
var firstToken = trivia2.GetStructure()!.GetFirstToken(includeZeroWidth: true);
if (ContainsOnlyWhitespace(firstToken.FullSpan.Start, firstToken.SpanStart))
{
token2 = firstToken;
}
}
}
/// <summary>
/// check whether string between start and end position only contains whitespace
/// </summary>
private bool ContainsOnlyWhitespace(int start, int end)
{
var span = TextSpan.FromBounds(start, end);
for (var i = span.Start - this.Token1.Span.End; i < span.Length; i++)
{
if (!char.IsWhiteSpace(this.OriginalString[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// check whether first line between two tokens contains only whitespace
/// </summary>
private bool FirstLineBlank()
{
// if we see elastic trivia as the first trivia in the trivia list,
// we consider it as blank line
if (this.Token1.TrailingTrivia.Count > 0 &&
this.Token1.TrailingTrivia[0].IsElastic())
{
return true;
}
var index = this.OriginalString.IndexOf(this.IsNewLine);
if (index < 0)
{
return IsNullOrWhitespace(this.OriginalString);
}
for (var i = 0; i < index; i++)
{
if (!IsWhitespace(this.OriginalString[i]))
{
return false;
}
}
return true;
}
private LineColumnDelta Apply(
LineColumn lineColumnBeforeTrivia1, SyntaxTrivia trivia1, LineColumn lineColumnAfterTrivia1, LineColumnDelta existingWhitespaceBetween, SyntaxTrivia trivia2, LineColumnRule rule)
{
// we do not touch spaces adjacent to missing token
// [missing token] [whitespace] [trivia] or [trivia] [whitespace] [missing token] case
if ((this.Token1.IsMissing && trivia1.RawKind == 0) ||
(trivia2.RawKind == 0 && this.Token2.IsMissing))
{
// leave things as it is
return existingWhitespaceBetween;
}
var lines = GetRuleLines(rule, lineColumnAfterTrivia1, existingWhitespaceBetween);
var spaceOrIndentations = GetRuleSpacesOrIndentation(lineColumnBeforeTrivia1, lineColumnAfterTrivia1, existingWhitespaceBetween, trivia2, rule);
return new LineColumnDelta(
lines,
spaceOrIndentations,
whitespaceOnly: true,
forceUpdate: existingWhitespaceBetween.ForceUpdate);
}
private int GetRuleSpacesOrIndentation(
LineColumn lineColumnBeforeTrivia1, LineColumn lineColumnAfterTrivia1, LineColumnDelta existingWhitespaceBetween, SyntaxTrivia trivia2, LineColumnRule rule)
{
var lineColumnAfterExistingWhitespace = lineColumnAfterTrivia1.With(existingWhitespaceBetween);
// next trivia is moved to next line or already on a new line, use indentation
if (rule.Lines > 0 || lineColumnAfterExistingWhitespace.WhitespaceOnly)
{
return rule.IndentationOperation switch
{
LineColumnRule.IndentationOperations.Absolute => Math.Max(0, rule.Indentation),
LineColumnRule.IndentationOperations.Default => this.Context.GetBaseIndentation(trivia2.RawKind == 0 ? this.EndPosition : trivia2.SpanStart),
LineColumnRule.IndentationOperations.Given => (trivia2.RawKind == 0) ? this.Spaces : Math.Max(0, _indentation),
LineColumnRule.IndentationOperations.Follow => Math.Max(0, lineColumnBeforeTrivia1.Column),
LineColumnRule.IndentationOperations.Preserve => existingWhitespaceBetween.Spaces,
_ => throw ExceptionUtilities.UnexpectedValue(rule.IndentationOperation),
};
}
// okay, we are not on a its own line, use space information
return rule.SpaceOperation switch
{
LineColumnRule.SpaceOperations.Preserve => Math.Max(rule.Spaces, existingWhitespaceBetween.Spaces),
LineColumnRule.SpaceOperations.Force => Math.Max(rule.Spaces, 0),
_ => throw ExceptionUtilities.UnexpectedValue(rule.SpaceOperation),
};
}
private static int GetRuleLines(LineColumnRule rule, LineColumn lineColumnAfterTrivia1, LineColumnDelta existingWhitespaceBetween)
{
var adjustedRuleLines = Math.Max(0, rule.Lines - GetTrailingLinesAtEndOfTrivia1(lineColumnAfterTrivia1));
return (rule.LineOperation == LineColumnRule.LineOperations.Preserve) ? Math.Max(adjustedRuleLines, existingWhitespaceBetween.Lines) : adjustedRuleLines;
}
private int GetIndentation()
{
var lastText = this.OriginalString.GetLastLineText();
var initialColumn = (lastText == this.OriginalString) ? this.InitialLineColumn.Column : 0;
var index = lastText.GetFirstNonWhitespaceIndexInString();
if (index < 0)
{
return this.Spaces;
}
var position = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, index);
var tokenPosition = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, lastText.Length);
return this.Spaces - (tokenPosition - position);
}
/// <summary>
/// return 0 or 1 based on line column of the trivia1's end point
/// this is based on our structured trivia's implementation detail that some structured trivia can have
/// one new line at the end of the trivia
/// </summary>
private static int GetTrailingLinesAtEndOfTrivia1(LineColumn lineColumnAfterTrivia1)
=> (lineColumnAfterTrivia1.Column == 0 && lineColumnAfterTrivia1.Line > 0) ? 1 : 0;
private void AddExtraLines(int linesBetweenTokens, ArrayBuilder<SyntaxTrivia> changes)
{
if (linesBetweenTokens < this.LineBreaks)
{
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var lineBreaks);
AddWhitespaceTrivia(
LineColumn.Default,
new LineColumnDelta(lines: this.LineBreaks - linesBetweenTokens, spaces: 0),
lineBreaks);
var insertionIndex = GetInsertionIndex(changes);
for (var i = lineBreaks.Count - 1; i >= 0; i--)
changes.Insert(insertionIndex, lineBreaks[i]);
}
}
private int GetInsertionIndex(ArrayBuilder<SyntaxTrivia> changes)
{
// first line is blank or there is no changes.
// just insert at the head
if (_firstLineBlank ||
changes.Count == 0)
{
return 0;
}
// try to find end of line
for (var i = changes.Count - 1; i >= 0; i--)
{
// insert right after existing end of line trivia
if (IsEndOfLine(changes[i]))
{
return i + 1;
}
}
// can't find any line, put blank line right after any trivia that has lines in them
for (var i = changes.Count - 1; i >= 0; i--)
{
if (changes[i].ToFullString().ContainsLineBreak())
{
return i + 1;
}
}
// well, give up and insert at the top
return 0;
}
private void AddExtraLines(int linesBetweenTokens, ArrayBuilder<TextChange> changes)
{
if (linesBetweenTokens >= this.LineBreaks)
{
return;
}
if (changes.Count == 0)
{
AddWhitespaceTextChange(
LineColumn.Default, new LineColumnDelta(lines: this.LineBreaks - linesBetweenTokens, spaces: 0),
GetInsertionSpan(changes), changes);
return;
}
if (TryGetMatchingChangeIndex(changes, out var index))
{
// already change exist at same position that contains only whitespace
var delta = GetLineColumnDelta(0, changes[index].NewText ?? "");
changes[index] = GetWhitespaceTextChange(
LineColumn.Default,
new LineColumnDelta(lines: this.LineBreaks + delta.Lines - linesBetweenTokens, spaces: delta.Spaces),
changes[index].Span);
return;
}
else
{
var change = GetWhitespaceTextChange(
LineColumn.Default,
new LineColumnDelta(lines: this.LineBreaks - linesBetweenTokens, spaces: 0),
GetInsertionSpan(changes));
changes.Insert(0, change);
return;
}
}
private bool TryGetMatchingChangeIndex(ArrayBuilder<TextChange> changes, out int index)
{
index = -1;
var insertionPoint = GetInsertionSpan(changes);
for (var i = 0; i < changes.Count; i++)
{
var change = changes[i];
if (change.Span.Contains(insertionPoint) && IsNullOrWhitespace(change.NewText))
{
index = i;
return true;
}
}
return false;
}
private TextSpan GetInsertionSpan(ArrayBuilder<TextChange> changes)
{
// first line is blank or there is no changes.
// just insert at the head
if (_firstLineBlank ||
changes.Count == 0)
{
return new TextSpan(this.StartPosition, 0);
}
// try to find end of line
for (var i = this.OriginalString.Length - 1; i >= 0; i--)
{
if (this.OriginalString[i] == '\n')
{
return new TextSpan(Math.Min(this.StartPosition + i + 1, this.EndPosition), 0);
}
}
// well, give up and insert at the top
Debug.Assert(!_firstLineBlank);
return new TextSpan(this.EndPosition, 0);
}
private void AddWhitespaceTrivia(
LineColumn lineColumn,
LineColumnDelta delta,
ArrayBuilder<SyntaxTrivia> changes)
{
AddWhitespaceTrivia(lineColumn, delta, default, changes);
}
private void AddWhitespaceTrivia(
LineColumn lineColumn,
LineColumnDelta delta,
TextSpan notUsed,
ArrayBuilder<SyntaxTrivia> changes)
{
if (delta.Lines == 0 && delta.Spaces == 0)
{
// remove trivia
return;
}
for (var i = 0; i < delta.Lines; i++)
{
changes.Add(CreateEndOfLine());
}
if (delta.Spaces == 0)
{
return;
}
var useTabs = this.Options.GetOption(FormattingOptions2.UseTabs);
var tabSize = this.Options.GetOption(FormattingOptions2.TabSize);
// space indicates indentation
if (delta.Lines > 0 || lineColumn.Column == 0)
{
changes.Add(CreateWhitespace(delta.Spaces.CreateIndentationString(useTabs, tabSize)));
return;
}
// space indicates space between two noisy trivia or tokens
changes.Add(CreateWhitespace(GetSpaces(delta.Spaces)));
}
private string GetWhitespaceString(LineColumn lineColumn, LineColumnDelta delta)
{
var sb = StringBuilderPool.Allocate();
var newLine = this.Options.GetOption(FormattingOptions2.NewLine);
for (var i = 0; i < delta.Lines; i++)
{
sb.Append(newLine);
}
if (delta.Spaces == 0)
{
return StringBuilderPool.ReturnAndFree(sb);
}
var useTabs = this.Options.GetOption(FormattingOptions2.UseTabs);
var tabSize = this.Options.GetOption(FormattingOptions2.TabSize);
// space indicates indentation
if (delta.Lines > 0 || lineColumn.Column == 0)
{
sb.AppendIndentationString(delta.Spaces, useTabs, tabSize);
return StringBuilderPool.ReturnAndFree(sb);
}
// space indicates space between two noisy trivia or tokens
sb.Append(' ', repeatCount: delta.Spaces);
return StringBuilderPool.ReturnAndFree(sb);
}
private TextChange GetWhitespaceTextChange(LineColumn lineColumn, LineColumnDelta delta, TextSpan span)
=> new(span, GetWhitespaceString(lineColumn, delta));
private void AddWhitespaceTextChange(LineColumn lineColumn, LineColumnDelta delta, TextSpan span, ArrayBuilder<TextChange> changes)
{
var newText = GetWhitespaceString(lineColumn, delta);
changes.Add(new TextChange(span, newText));
}
private TextSpan GetTextSpan(SyntaxTrivia trivia1, SyntaxTrivia trivia2)
{
if (trivia1.RawKind == 0)
{
return TextSpan.FromBounds(this.StartPosition, trivia2.FullSpan.Start);
}
if (trivia2.RawKind == 0)
{
return TextSpan.FromBounds(trivia1.FullSpan.End, this.EndPosition);
}
return TextSpan.FromBounds(trivia1.FullSpan.End, trivia2.FullSpan.Start);
}
private bool IsWhitespaceOrEndOfLine(SyntaxTrivia trivia)
=> IsWhitespace(trivia) || IsEndOfLine(trivia);
private LineColumnDelta GetLineColumnOfWhitespace(
LineColumn lineColumn,
SyntaxTrivia previousTrivia,
SyntaxTrivia trivia1,
LineColumnDelta whitespaceBetween,
SyntaxTrivia trivia2)
{
Debug.Assert(IsWhitespaceOrEndOfLine(trivia2));
// treat elastic as new line as long as its previous trivia is not elastic or
// it has line break right before it
if (trivia2.IsElastic())
{
// eat up consecutive elastic trivia or next line
if (trivia1.IsElastic() || IsEndOfLine(trivia1))
{
return LineColumnDelta.Default;
}
// if there was already new lines, ignore elastic
var lineColumnAfterPreviousTrivia = GetLineColumn(lineColumn, previousTrivia);
var newLineFromPreviousOperation = (whitespaceBetween.Lines > 0) ||
(lineColumnAfterPreviousTrivia.Line > 0 && lineColumnAfterPreviousTrivia.Column == 0);
if (newLineFromPreviousOperation && whitespaceBetween.WhitespaceOnly)
{
return LineColumnDelta.Default;
}
return new LineColumnDelta(lines: 1, spaces: 0, whitespaceOnly: true, forceUpdate: true);
}
if (IsEndOfLine(trivia2))
{
return new LineColumnDelta(lines: 1, spaces: 0, whitespaceOnly: true, forceUpdate: false);
}
var text = trivia2.ToFullString();
return new LineColumnDelta(
lines: 0,
spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), lineColumn.With(whitespaceBetween).Column, text.Length),
whitespaceOnly: true,
forceUpdate: false);
}
private LineColumn GetInitialLineColumn()
{
var tokenText = this.Token1.ToString();
var initialColumn = this.Token1.RawKind == 0 ? 0 : this.TokenStream.GetCurrentColumn(this.Token1);
var delta = GetLineColumnDelta(initialColumn, tokenText);
return new LineColumn(line: 0, column: initialColumn + delta.Spaces, whitespaceOnly: delta.WhitespaceOnly);
}
protected LineColumn GetLineColumn(LineColumn lineColumn, SyntaxTrivia trivia)
{
var text = trivia.ToFullString();
return lineColumn.With(GetLineColumnDelta(lineColumn.Column, text));
}
protected LineColumnDelta GetLineColumnDelta(LineColumn lineColumn, SyntaxTrivia trivia)
{
var text = trivia.ToFullString();
return GetLineColumnDelta(lineColumn.Column, text);
}
protected LineColumnDelta GetLineColumnDelta(int initialColumn, string text)
{
var lineText = text.GetLastLineText();
if (text != lineText)
{
return new LineColumnDelta(
lines: text.GetNumberOfLineBreaks(),
spaces: lineText.GetColumnFromLineOffset(lineText.Length, this.Options.GetOption(FormattingOptions2.TabSize)),
whitespaceOnly: IsNullOrWhitespace(lineText));
}
return new LineColumnDelta(
lines: 0,
spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, text.Length),
whitespaceOnly: IsNullOrWhitespace(lineText));
}
protected int GetExistingIndentation(SyntaxTrivia trivia)
{
var offset = trivia.FullSpan.Start - this.StartPosition;
var originalText = this.OriginalString.Substring(0, offset);
var delta = GetLineColumnDelta(this.InitialLineColumn.Column, originalText);
return this.InitialLineColumn.With(delta).Column;
}
private static string GetSpaces(int space)
{
if (space >= 0 && space < 20)
{
return s_spaceCache[space];
}
return new string(' ', space);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract class AbstractTriviaFormatter
{
#region Caches
private static readonly string[] s_spaceCache;
/// <summary>
/// set up space string caches
/// </summary>
static AbstractTriviaFormatter()
{
s_spaceCache = new string[20];
for (var i = 0; i < 20; i++)
{
s_spaceCache[i] = new string(' ', i);
}
}
#endregion
/// <summary>
/// format the trivia at the line column and put changes to the changes
/// </summary>
private delegate LineColumnDelta Formatter<T>(LineColumn lineColumn, SyntaxTrivia trivia, ArrayBuilder<T> changes, CancellationToken cancellationToken);
/// <summary>
/// create whitespace for the delta at the line column and put changes to the changes
/// </summary>
private delegate void WhitespaceAppender<T>(LineColumn lineColumn, LineColumnDelta delta, TextSpan span, ArrayBuilder<T> changes);
protected readonly FormattingContext Context;
protected readonly ChainedFormattingRules FormattingRules;
protected readonly string OriginalString;
protected readonly int LineBreaks;
protected readonly int Spaces;
protected readonly LineColumn InitialLineColumn;
protected readonly SyntaxToken Token1;
protected readonly SyntaxToken Token2;
private readonly int _indentation;
private readonly bool _firstLineBlank;
public AbstractTriviaFormatter(
FormattingContext context,
ChainedFormattingRules formattingRules,
SyntaxToken token1,
SyntaxToken token2,
string originalString,
int lineBreaks,
int spaces)
{
Contract.ThrowIfNull(context);
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(originalString);
Contract.ThrowIfFalse(lineBreaks >= 0);
Contract.ThrowIfFalse(spaces >= 0);
Contract.ThrowIfTrue(token1 == default && token2 == default);
this.Context = context;
this.FormattingRules = formattingRules;
this.OriginalString = originalString;
this.Token1 = token1;
this.Token2 = token2;
this.LineBreaks = lineBreaks;
this.Spaces = spaces;
this.InitialLineColumn = GetInitialLineColumn();
// "Spaces" holds either space counts between two tokens if two are on same line or indentation of token2 if
// two are on different line. but actual "Indentation" of the line could be different than "Spaces" if there is
// noisy trivia before token2 on the same line.
// this.indentation indicates that trivia's indentation
//
// ex) [indentation]/** */ token2
// [spaces ]
_indentation = (this.LineBreaks > 0) ? GetIndentation() : -1;
// check whether first line between two tokens contains only whitespace
// depends on this we decide where to insert blank lines at the end
_firstLineBlank = FirstLineBlank();
}
/// <summary>
/// return whether this formatting succeeded or not
/// for example, if there is skipped tokens in one of trivia between tokens
/// we consider formatting this region is failed
/// </summary>
protected abstract bool Succeeded();
/// <summary>
/// check whether given trivia is whitespace trivia or not
/// </summary>
protected abstract bool IsWhitespace(SyntaxTrivia trivia);
/// <summary>
/// check whether given trivia is end of line trivia or not
/// </summary>
protected abstract bool IsEndOfLine(SyntaxTrivia trivia);
/// <summary>
/// check whether given string is either null or whitespace
/// </summary>
protected bool IsNullOrWhitespace([NotNullWhen(true)] string? text)
{
if (text == null)
{
return true;
}
for (var i = 0; i < text.Length; i++)
{
if (!IsWhitespace(text[i]) || !IsNewLine(text[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// check whether given char is whitespace
/// </summary>
protected abstract bool IsWhitespace(char ch);
/// <summary>
/// check whether given char is new line char
/// </summary>
protected abstract bool IsNewLine(char ch);
/// <summary>
/// create whitespace trivia
/// </summary>
protected abstract SyntaxTrivia CreateWhitespace(string text);
/// <summary>
/// create end of line trivia
/// </summary>
protected abstract SyntaxTrivia CreateEndOfLine();
/// <summary>
/// return line column rule for the given two trivia
/// </summary>
protected abstract LineColumnRule GetLineColumnRuleBetween(SyntaxTrivia trivia1, LineColumnDelta existingWhitespaceBetween, bool implicitLineBreak, SyntaxTrivia trivia2);
/// <summary>
/// format the given trivia at the line column position and put result to the changes list
/// </summary>
protected abstract LineColumnDelta Format(LineColumn lineColumn, SyntaxTrivia trivia, ArrayBuilder<SyntaxTrivia> changes, CancellationToken cancellationToken);
/// <summary>
/// format the given trivia at the line column position and put text change result to the changes list
/// </summary>
protected abstract LineColumnDelta Format(LineColumn lineColumn, SyntaxTrivia trivia, ArrayBuilder<TextChange> changes, CancellationToken cancellationToken);
/// <summary>
/// returns true if the trivia contains a Line break
/// </summary>
protected abstract bool ContainsImplicitLineBreak(SyntaxTrivia trivia);
protected int StartPosition
{
get
{
if (this.Token1.RawKind == 0)
{
return this.TreeInfo.StartPosition;
}
return this.Token1.Span.End;
}
}
protected int EndPosition
{
get
{
if (this.Token2.RawKind == 0)
{
return this.TreeInfo.EndPosition;
}
return this.Token2.SpanStart;
}
}
protected TreeData TreeInfo
{
get { return this.Context.TreeData; }
}
protected AnalyzerConfigOptions Options
{
get { return this.Context.Options; }
}
protected TokenStream TokenStream
{
get { return this.Context.TokenStream; }
}
public SyntaxTriviaList FormatToSyntaxTrivia(CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var triviaList);
var lineColumn = FormatTrivia(Format, AddWhitespaceTrivia, triviaList, cancellationToken);
// deal with edges
// insert empty linebreaks at the beginning of trivia list
AddExtraLines(lineColumn.Line, triviaList);
if (Succeeded())
{
return new SyntaxTriviaList(triviaList);
}
triviaList.Clear();
AddRange(triviaList, this.Token1.TrailingTrivia);
AddRange(triviaList, this.Token2.LeadingTrivia);
return new SyntaxTriviaList(triviaList);
}
private static void AddRange(ArrayBuilder<SyntaxTrivia> result, SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
result.Add(trivia);
}
public ImmutableArray<TextChange> FormatToTextChanges(CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<TextChange>.GetInstance(out var changes);
var lineColumn = FormatTrivia(Format, AddWhitespaceTextChange, changes, cancellationToken);
// deal with edges
// insert empty linebreaks at the beginning of trivia list
AddExtraLines(lineColumn.Line, changes);
if (Succeeded())
{
return changes.ToImmutable();
}
return ImmutableArray<TextChange>.Empty;
}
private LineColumn FormatTrivia<T>(Formatter<T> formatter, WhitespaceAppender<T> whitespaceAdder, ArrayBuilder<T> changes, CancellationToken cancellationToken)
{
var lineColumn = this.InitialLineColumn;
var existingWhitespaceDelta = LineColumnDelta.Default;
var previousWhitespaceTrivia = default(SyntaxTrivia);
var previousTrivia = default(SyntaxTrivia);
var implicitLineBreak = false;
var list = new TriviaList(this.Token1.TrailingTrivia, this.Token2.LeadingTrivia);
foreach (var trivia in list)
{
if (trivia.RawKind == 0)
{
continue;
}
if (IsWhitespaceOrEndOfLine(trivia))
{
if (IsEndOfLine(trivia))
{
implicitLineBreak = false;
}
existingWhitespaceDelta = existingWhitespaceDelta.With(
GetLineColumnOfWhitespace(
lineColumn,
previousTrivia,
previousWhitespaceTrivia,
existingWhitespaceDelta,
trivia));
previousWhitespaceTrivia = trivia;
continue;
}
previousWhitespaceTrivia = default;
lineColumn = FormatFirstTriviaAndWhitespaceAfter(
lineColumn,
previousTrivia, existingWhitespaceDelta, trivia,
formatter, whitespaceAdder,
changes, implicitLineBreak, cancellationToken);
implicitLineBreak = implicitLineBreak || ContainsImplicitLineBreak(trivia);
existingWhitespaceDelta = LineColumnDelta.Default;
previousTrivia = trivia;
}
lineColumn = FormatFirstTriviaAndWhitespaceAfter(
lineColumn,
previousTrivia, existingWhitespaceDelta, default,
formatter, whitespaceAdder,
changes, implicitLineBreak, cancellationToken);
return lineColumn;
}
private LineColumn FormatFirstTriviaAndWhitespaceAfter<T>(
LineColumn lineColumnBeforeTrivia1,
SyntaxTrivia trivia1,
LineColumnDelta existingWhitespaceBetween,
SyntaxTrivia trivia2,
Formatter<T> format,
WhitespaceAppender<T> addWhitespaceTrivia,
ArrayBuilder<T> changes,
bool implicitLineBreak,
CancellationToken cancellationToken)
{
var lineColumnAfterTrivia1 = trivia1.RawKind == 0 ?
lineColumnBeforeTrivia1 : lineColumnBeforeTrivia1.With(format(lineColumnBeforeTrivia1, trivia1, changes, cancellationToken));
var rule = GetOverallLineColumnRuleBetween(trivia1, existingWhitespaceBetween, implicitLineBreak, trivia2);
var whitespaceDelta = Apply(lineColumnBeforeTrivia1, trivia1, lineColumnAfterTrivia1, existingWhitespaceBetween, trivia2, rule);
var span = GetTextSpan(trivia1, trivia2);
addWhitespaceTrivia(lineColumnAfterTrivia1, whitespaceDelta, span, changes);
return lineColumnAfterTrivia1.With(whitespaceDelta);
}
/// <summary>
/// get line column rule between two trivia
/// </summary>
private LineColumnRule GetOverallLineColumnRuleBetween(SyntaxTrivia trivia1, LineColumnDelta existingWhitespaceBetween, bool implicitLineBreak, SyntaxTrivia trivia2)
{
var defaultRule = GetLineColumnRuleBetween(trivia1, existingWhitespaceBetween, implicitLineBreak, trivia2);
GetTokensAtEdgeOfStructureTrivia(trivia1, trivia2, out var token1, out var token2);
// if there are tokens, try formatting rules to see whether there is a user supplied one
if (token1.RawKind == 0 || token2.RawKind == 0)
{
return defaultRule;
}
// use line defined by the token formatting rules
var lineOperation = this.FormattingRules.GetAdjustNewLinesOperation(token1, token2);
// there is existing lines, but no line operation
if (existingWhitespaceBetween.Lines != 0 && lineOperation == null)
{
return defaultRule;
}
if (lineOperation != null)
{
switch (lineOperation.Option)
{
case AdjustNewLinesOption.PreserveLines:
if (existingWhitespaceBetween.Lines != 0)
{
return defaultRule.With(lines: lineOperation.Line, lineOperation: LineColumnRule.LineOperations.Preserve);
}
break;
case AdjustNewLinesOption.ForceLines:
return defaultRule.With(lines: lineOperation.Line, lineOperation: LineColumnRule.LineOperations.Force);
case AdjustNewLinesOption.ForceLinesIfOnSingleLine:
if (this.Context.TokenStream.TwoTokensOnSameLine(token1, token2))
{
return defaultRule.With(lines: lineOperation.Line, lineOperation: LineColumnRule.LineOperations.Force);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(lineOperation.Option);
}
}
// use space defined by the regular formatting rules
var spaceOperation = this.FormattingRules.GetAdjustSpacesOperation(token1, token2);
if (spaceOperation == null)
{
return defaultRule;
}
if (spaceOperation.Option == AdjustSpacesOption.DefaultSpacesIfOnSingleLine &&
spaceOperation.Space == 1)
{
return defaultRule;
}
return defaultRule.With(spaces: spaceOperation.Space);
}
/// <summary>
/// if the given trivia is the very first or the last trivia between two normal tokens and
/// if the trivia is structured trivia, get one token that belongs to the structured trivia and one belongs to the normal token stream
/// </summary>
private void GetTokensAtEdgeOfStructureTrivia(SyntaxTrivia trivia1, SyntaxTrivia trivia2, out SyntaxToken token1, out SyntaxToken token2)
{
token1 = default;
if (trivia1.RawKind == 0)
{
token1 = this.Token1;
}
else if (trivia1.HasStructure)
{
var lastToken = trivia1.GetStructure()!.GetLastToken(includeZeroWidth: true);
if (ContainsOnlyWhitespace(lastToken.Span.End, lastToken.FullSpan.End))
{
token1 = lastToken;
}
}
token2 = default;
if (trivia2.RawKind == 0)
{
token2 = this.Token2;
}
else if (trivia2.HasStructure)
{
var firstToken = trivia2.GetStructure()!.GetFirstToken(includeZeroWidth: true);
if (ContainsOnlyWhitespace(firstToken.FullSpan.Start, firstToken.SpanStart))
{
token2 = firstToken;
}
}
}
/// <summary>
/// check whether string between start and end position only contains whitespace
/// </summary>
private bool ContainsOnlyWhitespace(int start, int end)
{
var span = TextSpan.FromBounds(start, end);
for (var i = span.Start - this.Token1.Span.End; i < span.Length; i++)
{
if (!char.IsWhiteSpace(this.OriginalString[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// check whether first line between two tokens contains only whitespace
/// </summary>
private bool FirstLineBlank()
{
// if we see elastic trivia as the first trivia in the trivia list,
// we consider it as blank line
if (this.Token1.TrailingTrivia.Count > 0 &&
this.Token1.TrailingTrivia[0].IsElastic())
{
return true;
}
var index = this.OriginalString.IndexOf(this.IsNewLine);
if (index < 0)
{
return IsNullOrWhitespace(this.OriginalString);
}
for (var i = 0; i < index; i++)
{
if (!IsWhitespace(this.OriginalString[i]))
{
return false;
}
}
return true;
}
private LineColumnDelta Apply(
LineColumn lineColumnBeforeTrivia1, SyntaxTrivia trivia1, LineColumn lineColumnAfterTrivia1, LineColumnDelta existingWhitespaceBetween, SyntaxTrivia trivia2, LineColumnRule rule)
{
// we do not touch spaces adjacent to missing token
// [missing token] [whitespace] [trivia] or [trivia] [whitespace] [missing token] case
if ((this.Token1.IsMissing && trivia1.RawKind == 0) ||
(trivia2.RawKind == 0 && this.Token2.IsMissing))
{
// leave things as it is
return existingWhitespaceBetween;
}
var lines = GetRuleLines(rule, lineColumnAfterTrivia1, existingWhitespaceBetween);
var spaceOrIndentations = GetRuleSpacesOrIndentation(lineColumnBeforeTrivia1, lineColumnAfterTrivia1, existingWhitespaceBetween, trivia2, rule);
return new LineColumnDelta(
lines,
spaceOrIndentations,
whitespaceOnly: true,
forceUpdate: existingWhitespaceBetween.ForceUpdate);
}
private int GetRuleSpacesOrIndentation(
LineColumn lineColumnBeforeTrivia1, LineColumn lineColumnAfterTrivia1, LineColumnDelta existingWhitespaceBetween, SyntaxTrivia trivia2, LineColumnRule rule)
{
var lineColumnAfterExistingWhitespace = lineColumnAfterTrivia1.With(existingWhitespaceBetween);
// next trivia is moved to next line or already on a new line, use indentation
if (rule.Lines > 0 || lineColumnAfterExistingWhitespace.WhitespaceOnly)
{
return rule.IndentationOperation switch
{
LineColumnRule.IndentationOperations.Absolute => Math.Max(0, rule.Indentation),
LineColumnRule.IndentationOperations.Default => this.Context.GetBaseIndentation(trivia2.RawKind == 0 ? this.EndPosition : trivia2.SpanStart),
LineColumnRule.IndentationOperations.Given => (trivia2.RawKind == 0) ? this.Spaces : Math.Max(0, _indentation),
LineColumnRule.IndentationOperations.Follow => Math.Max(0, lineColumnBeforeTrivia1.Column),
LineColumnRule.IndentationOperations.Preserve => existingWhitespaceBetween.Spaces,
_ => throw ExceptionUtilities.UnexpectedValue(rule.IndentationOperation),
};
}
// okay, we are not on a its own line, use space information
return rule.SpaceOperation switch
{
LineColumnRule.SpaceOperations.Preserve => Math.Max(rule.Spaces, existingWhitespaceBetween.Spaces),
LineColumnRule.SpaceOperations.Force => Math.Max(rule.Spaces, 0),
_ => throw ExceptionUtilities.UnexpectedValue(rule.SpaceOperation),
};
}
private static int GetRuleLines(LineColumnRule rule, LineColumn lineColumnAfterTrivia1, LineColumnDelta existingWhitespaceBetween)
{
var adjustedRuleLines = Math.Max(0, rule.Lines - GetTrailingLinesAtEndOfTrivia1(lineColumnAfterTrivia1));
return (rule.LineOperation == LineColumnRule.LineOperations.Preserve) ? Math.Max(adjustedRuleLines, existingWhitespaceBetween.Lines) : adjustedRuleLines;
}
private int GetIndentation()
{
var lastText = this.OriginalString.GetLastLineText();
var initialColumn = (lastText == this.OriginalString) ? this.InitialLineColumn.Column : 0;
var index = lastText.GetFirstNonWhitespaceIndexInString();
if (index < 0)
{
return this.Spaces;
}
var position = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, index);
var tokenPosition = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, lastText.Length);
return this.Spaces - (tokenPosition - position);
}
/// <summary>
/// return 0 or 1 based on line column of the trivia1's end point
/// this is based on our structured trivia's implementation detail that some structured trivia can have
/// one new line at the end of the trivia
/// </summary>
private static int GetTrailingLinesAtEndOfTrivia1(LineColumn lineColumnAfterTrivia1)
=> (lineColumnAfterTrivia1.Column == 0 && lineColumnAfterTrivia1.Line > 0) ? 1 : 0;
private void AddExtraLines(int linesBetweenTokens, ArrayBuilder<SyntaxTrivia> changes)
{
if (linesBetweenTokens < this.LineBreaks)
{
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var lineBreaks);
AddWhitespaceTrivia(
LineColumn.Default,
new LineColumnDelta(lines: this.LineBreaks - linesBetweenTokens, spaces: 0),
lineBreaks);
var insertionIndex = GetInsertionIndex(changes);
for (var i = lineBreaks.Count - 1; i >= 0; i--)
changes.Insert(insertionIndex, lineBreaks[i]);
}
}
private int GetInsertionIndex(ArrayBuilder<SyntaxTrivia> changes)
{
// first line is blank or there is no changes.
// just insert at the head
if (_firstLineBlank ||
changes.Count == 0)
{
return 0;
}
// try to find end of line
for (var i = changes.Count - 1; i >= 0; i--)
{
// insert right after existing end of line trivia
if (IsEndOfLine(changes[i]))
{
return i + 1;
}
}
// can't find any line, put blank line right after any trivia that has lines in them
for (var i = changes.Count - 1; i >= 0; i--)
{
if (changes[i].ToFullString().ContainsLineBreak())
{
return i + 1;
}
}
// well, give up and insert at the top
return 0;
}
private void AddExtraLines(int linesBetweenTokens, ArrayBuilder<TextChange> changes)
{
if (linesBetweenTokens >= this.LineBreaks)
{
return;
}
if (changes.Count == 0)
{
AddWhitespaceTextChange(
LineColumn.Default, new LineColumnDelta(lines: this.LineBreaks - linesBetweenTokens, spaces: 0),
GetInsertionSpan(changes), changes);
return;
}
if (TryGetMatchingChangeIndex(changes, out var index))
{
// already change exist at same position that contains only whitespace
var delta = GetLineColumnDelta(0, changes[index].NewText ?? "");
changes[index] = GetWhitespaceTextChange(
LineColumn.Default,
new LineColumnDelta(lines: this.LineBreaks + delta.Lines - linesBetweenTokens, spaces: delta.Spaces),
changes[index].Span);
return;
}
else
{
var change = GetWhitespaceTextChange(
LineColumn.Default,
new LineColumnDelta(lines: this.LineBreaks - linesBetweenTokens, spaces: 0),
GetInsertionSpan(changes));
changes.Insert(0, change);
return;
}
}
private bool TryGetMatchingChangeIndex(ArrayBuilder<TextChange> changes, out int index)
{
index = -1;
var insertionPoint = GetInsertionSpan(changes);
for (var i = 0; i < changes.Count; i++)
{
var change = changes[i];
if (change.Span.Contains(insertionPoint) && IsNullOrWhitespace(change.NewText))
{
index = i;
return true;
}
}
return false;
}
private TextSpan GetInsertionSpan(ArrayBuilder<TextChange> changes)
{
// first line is blank or there is no changes.
// just insert at the head
if (_firstLineBlank ||
changes.Count == 0)
{
return new TextSpan(this.StartPosition, 0);
}
// try to find end of line
for (var i = this.OriginalString.Length - 1; i >= 0; i--)
{
if (this.OriginalString[i] == '\n')
{
return new TextSpan(Math.Min(this.StartPosition + i + 1, this.EndPosition), 0);
}
}
// well, give up and insert at the top
Debug.Assert(!_firstLineBlank);
return new TextSpan(this.EndPosition, 0);
}
private void AddWhitespaceTrivia(
LineColumn lineColumn,
LineColumnDelta delta,
ArrayBuilder<SyntaxTrivia> changes)
{
AddWhitespaceTrivia(lineColumn, delta, default, changes);
}
private void AddWhitespaceTrivia(
LineColumn lineColumn,
LineColumnDelta delta,
TextSpan notUsed,
ArrayBuilder<SyntaxTrivia> changes)
{
if (delta.Lines == 0 && delta.Spaces == 0)
{
// remove trivia
return;
}
for (var i = 0; i < delta.Lines; i++)
{
changes.Add(CreateEndOfLine());
}
if (delta.Spaces == 0)
{
return;
}
var useTabs = this.Options.GetOption(FormattingOptions2.UseTabs);
var tabSize = this.Options.GetOption(FormattingOptions2.TabSize);
// space indicates indentation
if (delta.Lines > 0 || lineColumn.Column == 0)
{
changes.Add(CreateWhitespace(delta.Spaces.CreateIndentationString(useTabs, tabSize)));
return;
}
// space indicates space between two noisy trivia or tokens
changes.Add(CreateWhitespace(GetSpaces(delta.Spaces)));
}
private string GetWhitespaceString(LineColumn lineColumn, LineColumnDelta delta)
{
var sb = StringBuilderPool.Allocate();
var newLine = this.Options.GetOption(FormattingOptions2.NewLine);
for (var i = 0; i < delta.Lines; i++)
{
sb.Append(newLine);
}
if (delta.Spaces == 0)
{
return StringBuilderPool.ReturnAndFree(sb);
}
var useTabs = this.Options.GetOption(FormattingOptions2.UseTabs);
var tabSize = this.Options.GetOption(FormattingOptions2.TabSize);
// space indicates indentation
if (delta.Lines > 0 || lineColumn.Column == 0)
{
sb.AppendIndentationString(delta.Spaces, useTabs, tabSize);
return StringBuilderPool.ReturnAndFree(sb);
}
// space indicates space between two noisy trivia or tokens
sb.Append(' ', repeatCount: delta.Spaces);
return StringBuilderPool.ReturnAndFree(sb);
}
private TextChange GetWhitespaceTextChange(LineColumn lineColumn, LineColumnDelta delta, TextSpan span)
=> new(span, GetWhitespaceString(lineColumn, delta));
private void AddWhitespaceTextChange(LineColumn lineColumn, LineColumnDelta delta, TextSpan span, ArrayBuilder<TextChange> changes)
{
var newText = GetWhitespaceString(lineColumn, delta);
changes.Add(new TextChange(span, newText));
}
private TextSpan GetTextSpan(SyntaxTrivia trivia1, SyntaxTrivia trivia2)
{
if (trivia1.RawKind == 0)
{
return TextSpan.FromBounds(this.StartPosition, trivia2.FullSpan.Start);
}
if (trivia2.RawKind == 0)
{
return TextSpan.FromBounds(trivia1.FullSpan.End, this.EndPosition);
}
return TextSpan.FromBounds(trivia1.FullSpan.End, trivia2.FullSpan.Start);
}
private bool IsWhitespaceOrEndOfLine(SyntaxTrivia trivia)
=> IsWhitespace(trivia) || IsEndOfLine(trivia);
private LineColumnDelta GetLineColumnOfWhitespace(
LineColumn lineColumn,
SyntaxTrivia previousTrivia,
SyntaxTrivia trivia1,
LineColumnDelta whitespaceBetween,
SyntaxTrivia trivia2)
{
Debug.Assert(IsWhitespaceOrEndOfLine(trivia2));
// treat elastic as new line as long as its previous trivia is not elastic or
// it has line break right before it
if (trivia2.IsElastic())
{
// eat up consecutive elastic trivia or next line
if (trivia1.IsElastic() || IsEndOfLine(trivia1))
{
return LineColumnDelta.Default;
}
// if there was already new lines, ignore elastic
var lineColumnAfterPreviousTrivia = GetLineColumn(lineColumn, previousTrivia);
var newLineFromPreviousOperation = (whitespaceBetween.Lines > 0) ||
(lineColumnAfterPreviousTrivia.Line > 0 && lineColumnAfterPreviousTrivia.Column == 0);
if (newLineFromPreviousOperation && whitespaceBetween.WhitespaceOnly)
{
return LineColumnDelta.Default;
}
return new LineColumnDelta(lines: 1, spaces: 0, whitespaceOnly: true, forceUpdate: true);
}
if (IsEndOfLine(trivia2))
{
return new LineColumnDelta(lines: 1, spaces: 0, whitespaceOnly: true, forceUpdate: false);
}
var text = trivia2.ToFullString();
return new LineColumnDelta(
lines: 0,
spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), lineColumn.With(whitespaceBetween).Column, text.Length),
whitespaceOnly: true,
forceUpdate: false);
}
private LineColumn GetInitialLineColumn()
{
var tokenText = this.Token1.ToString();
var initialColumn = this.Token1.RawKind == 0 ? 0 : this.TokenStream.GetCurrentColumn(this.Token1);
var delta = GetLineColumnDelta(initialColumn, tokenText);
return new LineColumn(line: 0, column: initialColumn + delta.Spaces, whitespaceOnly: delta.WhitespaceOnly);
}
protected LineColumn GetLineColumn(LineColumn lineColumn, SyntaxTrivia trivia)
{
var text = trivia.ToFullString();
return lineColumn.With(GetLineColumnDelta(lineColumn.Column, text));
}
protected LineColumnDelta GetLineColumnDelta(LineColumn lineColumn, SyntaxTrivia trivia)
{
var text = trivia.ToFullString();
return GetLineColumnDelta(lineColumn.Column, text);
}
protected LineColumnDelta GetLineColumnDelta(int initialColumn, string text)
{
var lineText = text.GetLastLineText();
if (text != lineText)
{
return new LineColumnDelta(
lines: text.GetNumberOfLineBreaks(),
spaces: lineText.GetColumnFromLineOffset(lineText.Length, this.Options.GetOption(FormattingOptions2.TabSize)),
whitespaceOnly: IsNullOrWhitespace(lineText));
}
return new LineColumnDelta(
lines: 0,
spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, text.Length),
whitespaceOnly: IsNullOrWhitespace(lineText));
}
protected int GetExistingIndentation(SyntaxTrivia trivia)
{
var offset = trivia.FullSpan.Start - this.StartPosition;
var originalText = this.OriginalString.Substring(0, offset);
var delta = GetLineColumnDelta(this.InitialLineColumn.Column, originalText);
return this.InitialLineColumn.With(delta).Column;
}
private static string GetSpaces(int space)
{
if (space >= 0 && space < 20)
{
return s_spaceCache[space];
}
return new string(' ', space);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/TestUtilities/LanguageServer/AbstractLanguageServerProtocolTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Test;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Roslyn.Test.Utilities
{
[UseExportProvider]
public abstract class AbstractLanguageServerProtocolTests
{
// TODO: remove WPF dependency (IEditorInlineRenameService)
private static readonly TestComposition s_composition = EditorTestCompositions.LanguageServerProtocolWpf
.AddParts(typeof(TestLspWorkspaceRegistrationService))
.AddParts(typeof(TestDocumentTrackingService))
.AddParts(typeof(TestExperimentationService))
.RemoveParts(typeof(MockWorkspaceEventListenerProvider));
[Export(typeof(ILspWorkspaceRegistrationService)), PartNotDiscoverable]
internal class TestLspWorkspaceRegistrationService : ILspWorkspaceRegistrationService
{
private Workspace? _workspace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLspWorkspaceRegistrationService()
{
}
public ImmutableArray<Workspace> GetAllRegistrations()
{
Contract.ThrowIfNull(_workspace, "No workspace has been registered");
return ImmutableArray.Create(_workspace);
}
public void Register(Workspace workspace)
{
Contract.ThrowIfTrue(_workspace != null);
_workspace = workspace;
}
}
private class TestSpanMapperProvider : IDocumentServiceProvider
{
TService IDocumentServiceProvider.GetService<TService>()
=> (TService)(object)new TestSpanMapper();
}
internal class TestSpanMapper : ISpanMappingService
{
private static readonly LinePositionSpan s_mappedLinePosition = new LinePositionSpan(new LinePosition(0, 0), new LinePosition(0, 5));
private static readonly string s_mappedFilePath = "c:\\MappedFile.cs";
internal static readonly string GeneratedFileName = "GeneratedFile.cs";
internal static readonly LSP.Location MappedFileLocation = new LSP.Location
{
Range = ProtocolConversions.LinePositionToRange(s_mappedLinePosition),
Uri = new Uri(s_mappedFilePath)
};
/// <summary>
/// LSP tests are simulating the new razor system which does support mapping import directives.
/// </summary>
public bool SupportsMappingImportDirectives => true;
public Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
ImmutableArray<MappedSpanResult> mappedResult = default;
if (document.Name == GeneratedFileName)
{
mappedResult = spans.Select(span => new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5))).ToImmutableArray();
}
return Task.FromResult(mappedResult);
}
public Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync(
Document oldDocument,
Document newDocument,
CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
protected class OrderLocations : Comparer<LSP.Location>
{
public override int Compare(LSP.Location x, LSP.Location y) => CompareLocations(x, y);
}
protected virtual TestComposition Composition => s_composition;
/// <summary>
/// Asserts two objects are equivalent by converting to JSON and ignoring whitespace.
/// </summary>
/// <typeparam name="T">the JSON object type.</typeparam>
/// <param name="expected">the expected object to be converted to JSON.</param>
/// <param name="actual">the actual object to be converted to JSON.</param>
public static void AssertJsonEquals<T>(T expected, T actual)
{
var expectedStr = JsonConvert.SerializeObject(expected);
var actualStr = JsonConvert.SerializeObject(actual);
AssertEqualIgnoringWhitespace(expectedStr, actualStr);
}
protected static void AssertEqualIgnoringWhitespace(string expected, string actual)
{
var expectedWithoutWhitespace = Regex.Replace(expected, @"\s+", string.Empty);
var actualWithoutWhitespace = Regex.Replace(actual, @"\s+", string.Empty);
Assert.Equal(expectedWithoutWhitespace, actualWithoutWhitespace);
}
/// <summary>
/// Assert that two location lists are equivalent.
/// Locations are not always returned in a consistent order so they must be sorted.
/// </summary>
protected static void AssertLocationsEqual(IEnumerable<LSP.Location> expectedLocations, IEnumerable<LSP.Location> actualLocations)
{
var orderedActualLocations = actualLocations.OrderBy(CompareLocations);
var orderedExpectedLocations = expectedLocations.OrderBy(CompareLocations);
AssertJsonEquals(orderedExpectedLocations, orderedActualLocations);
}
protected static int CompareLocations(LSP.Location l1, LSP.Location l2)
{
var compareDocument = l1.Uri.OriginalString.CompareTo(l2.Uri.OriginalString);
var compareRange = CompareRange(l1.Range, l2.Range);
return compareDocument != 0 ? compareDocument : compareRange;
}
protected static int CompareRange(LSP.Range r1, LSP.Range r2)
{
var compareLine = r1.Start.Line.CompareTo(r2.Start.Line);
var compareChar = r1.Start.Character.CompareTo(r2.Start.Character);
return compareLine != 0 ? compareLine : compareChar;
}
protected static string ApplyTextEdits(LSP.TextEdit[] edits, SourceText originalMarkup)
{
var text = originalMarkup;
foreach (var edit in edits)
{
var lines = text.Lines;
var startPosition = ProtocolConversions.PositionToLinePosition(edit.Range.Start);
var endPosition = ProtocolConversions.PositionToLinePosition(edit.Range.End);
var textSpan = lines.GetTextSpan(new LinePositionSpan(startPosition, endPosition));
text = text.Replace(textSpan, edit.NewText);
}
return text.ToString();
}
internal static LSP.SymbolInformation CreateSymbolInformation(LSP.SymbolKind kind, string name, LSP.Location location, Glyph glyph, string? containerName = null)
{
var info = new LSP.VSSymbolInformation()
{
Kind = kind,
Name = name,
Location = location,
Icon = new ImageElement(glyph.GetImageId()),
};
if (containerName != null)
{
info.ContainerName = containerName;
}
return info;
}
protected static LSP.TextDocumentIdentifier CreateTextDocumentIdentifier(Uri uri, ProjectId? projectContext = null)
{
var documentIdentifier = new LSP.VSTextDocumentIdentifier { Uri = uri };
if (projectContext != null)
{
documentIdentifier.ProjectContext =
new LSP.ProjectContext { Id = ProtocolConversions.ProjectIdToProjectContextId(projectContext) };
}
return documentIdentifier;
}
protected static LSP.TextDocumentPositionParams CreateTextDocumentPositionParams(LSP.Location caret, ProjectId? projectContext = null)
=> new LSP.TextDocumentPositionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri, projectContext),
Position = caret.Range.Start
};
protected static LSP.MarkupContent CreateMarkupContent(LSP.MarkupKind kind, string value)
=> new LSP.MarkupContent()
{
Kind = kind,
Value = value
};
protected static LSP.CompletionParams CreateCompletionParams(
LSP.Location caret,
LSP.VSCompletionInvokeKind invokeKind,
string triggerCharacter,
LSP.CompletionTriggerKind triggerKind)
=> new LSP.CompletionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.VSCompletionContext()
{
InvokeKind = invokeKind,
TriggerCharacter = triggerCharacter,
TriggerKind = triggerKind,
}
};
protected static async Task<LSP.VSCompletionItem> CreateCompletionItemAsync(
string label,
LSP.CompletionItemKind kind,
string[] tags,
LSP.CompletionParams request,
Document document,
bool preselect = false,
ImmutableArray<char>? commitCharacters = null,
LSP.TextEdit? textEdit = null,
string? insertText = null,
string? sortText = null,
string? filterText = null,
long resultId = 0)
{
var position = await document.GetPositionFromLinePositionAsync(
ProtocolConversions.PositionToLinePosition(request.Position), CancellationToken.None).ConfigureAwait(false);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(
request.Context, document, position, CancellationToken.None).ConfigureAwait(false);
var item = new LSP.VSCompletionItem()
{
TextEdit = textEdit,
InsertText = insertText,
FilterText = filterText ?? label,
Label = label,
SortText = sortText ?? label,
InsertTextFormat = LSP.InsertTextFormat.Plaintext,
Kind = kind,
Data = JObject.FromObject(new CompletionResolveData()
{
ResultId = resultId,
}),
Preselect = preselect
};
if (tags != null)
item.Icon = tags.ToImmutableArray().GetFirstGlyph().GetImageElement();
if (commitCharacters != null)
item.CommitCharacters = commitCharacters.Value.Select(c => c.ToString()).ToArray();
return item;
}
protected static LSP.TextEdit GenerateTextEdit(string newText, int startLine, int startChar, int endLine, int endChar)
=> new LSP.TextEdit
{
NewText = newText,
Range = new LSP.Range
{
Start = new LSP.Position { Line = startLine, Character = startChar },
End = new LSP.Position { Line = endLine, Character = endChar }
}
};
private protected static CodeActionResolveData CreateCodeActionResolveData(string uniqueIdentifier, LSP.Location location, IEnumerable<string>? customTags = null)
=> new CodeActionResolveData(uniqueIdentifier, customTags.ToImmutableArrayOrEmpty(), location.Range, CreateTextDocumentIdentifier(location.Uri));
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the markup.
/// </summary>
protected TestLspServer CreateTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.CSharp);
protected TestLspServer CreateVisualBasicTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.VisualBasic);
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the specified documents.
/// </summary>
protected TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(markups, out locations, LanguageNames.CSharp);
private TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations, string languageName)
{
var workspace = languageName switch
{
LanguageNames.CSharp => TestWorkspace.CreateCSharp(markups, composition: Composition),
LanguageNames.VisualBasic => TestWorkspace.CreateVisualBasic(markups, composition: Composition),
_ => throw new ArgumentException($"language name {languageName} is not valid for a test workspace"),
};
RegisterWorkspaceForLsp(workspace);
var solution = workspace.CurrentSolution;
foreach (var document in workspace.Documents)
{
solution = solution.WithDocumentFilePath(document.Id, GetDocumentFilePathFromName(document.Name));
}
workspace.ChangeSolution(solution);
locations = GetAnnotatedLocations(workspace, solution);
return new TestLspServer(workspace);
}
protected TestLspServer CreateXmlTestLspServer(string xmlContent, out Dictionary<string, IList<LSP.Location>> locations)
{
var workspace = TestWorkspace.Create(xmlContent, composition: Composition);
RegisterWorkspaceForLsp(workspace);
locations = GetAnnotatedLocations(workspace, workspace.CurrentSolution);
return new TestLspServer(workspace);
}
protected static void AddMappedDocument(Workspace workspace, string markup)
{
var generatedDocumentId = DocumentId.CreateNewId(workspace.CurrentSolution.ProjectIds.First());
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(SourceText.From(markup), version, TestSpanMapper.GeneratedFileName));
var generatedDocumentInfo = DocumentInfo.Create(generatedDocumentId, TestSpanMapper.GeneratedFileName, SpecializedCollections.EmptyReadOnlyList<string>(),
SourceCodeKind.Regular, loader, $"C:\\{TestSpanMapper.GeneratedFileName}", isGenerated: true, designTimeOnly: false, new TestSpanMapperProvider());
var newSolution = workspace.CurrentSolution.AddDocument(generatedDocumentInfo);
workspace.TryApplyChanges(newSolution);
}
private protected static void RegisterWorkspaceForLsp(TestWorkspace workspace)
{
var provider = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
provider.Register(workspace);
}
public static Dictionary<string, IList<LSP.Location>> GetAnnotatedLocations(TestWorkspace workspace, Solution solution)
{
var locations = new Dictionary<string, IList<LSP.Location>>();
foreach (var testDocument in workspace.Documents)
{
var document = solution.GetRequiredDocument(testDocument.Id);
var text = document.GetTextSynchronously(CancellationToken.None);
foreach (var (name, spans) in testDocument.AnnotatedSpans)
{
var locationsForName = locations.GetValueOrDefault(name, new List<LSP.Location>());
locationsForName.AddRange(spans.Select(span => ConvertTextSpanWithTextToLocation(span, text, new Uri(document.FilePath))));
// Linked files will return duplicate annotated Locations for each document that links to the same file.
// Since the test output only cares about the actual file, make sure we de-dupe before returning.
locations[name] = locationsForName.Distinct().ToList();
}
}
return locations;
static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri)
{
var location = new LSP.Location
{
Uri = documentUri,
Range = ProtocolConversions.TextSpanToRange(span, text),
};
return location;
}
}
private static RequestDispatcher CreateRequestDispatcher(TestWorkspace workspace)
{
var factory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>();
return factory.CreateRequestDispatcher();
}
private static RequestExecutionQueue CreateRequestQueue(TestWorkspace workspace)
{
var registrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
return new RequestExecutionQueue(NoOpLspLogger.Instance, registrationService, serverName: "Tests", "TestClient");
}
private static string GetDocumentFilePathFromName(string documentName)
=> "C:\\" + documentName;
private static LSP.DidChangeTextDocumentParams CreateDidChangeTextDocumentParams(
Uri documentUri,
ImmutableArray<(int startLine, int startColumn, int endLine, int endColumn, string text)> changes)
{
var changeEvents = changes.Select(change => new LSP.TextDocumentContentChangeEvent
{
Text = change.text,
Range = new LSP.Range
{
Start = new LSP.Position(change.startLine, change.startColumn),
End = new LSP.Position(change.endLine, change.endColumn)
}
}).ToArray();
return new LSP.DidChangeTextDocumentParams()
{
TextDocument = new LSP.VersionedTextDocumentIdentifier
{
Uri = documentUri
},
ContentChanges = changeEvents
};
}
private static LSP.DidOpenTextDocumentParams CreateDidOpenTextDocumentParams(Uri uri, string source)
=> new LSP.DidOpenTextDocumentParams
{
TextDocument = new LSP.TextDocumentItem
{
Text = source,
Uri = uri
}
};
private static LSP.DidCloseTextDocumentParams CreateDidCloseTextDocumentParams(Uri uri)
=> new LSP.DidCloseTextDocumentParams()
{
TextDocument = new LSP.TextDocumentIdentifier
{
Uri = uri
}
};
public sealed class TestLspServer : IDisposable
{
public readonly TestWorkspace TestWorkspace;
private readonly RequestDispatcher _requestDispatcher;
private readonly RequestExecutionQueue _executionQueue;
internal TestLspServer(TestWorkspace testWorkspace)
{
TestWorkspace = testWorkspace;
_requestDispatcher = CreateRequestDispatcher(testWorkspace);
_executionQueue = CreateRequestQueue(testWorkspace);
}
public Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(string methodName, RequestType request, LSP.ClientCapabilities clientCapabilities,
string? clientName, CancellationToken cancellationToken) where RequestType : class
{
return _requestDispatcher.ExecuteRequestAsync<RequestType, ResponseType>(
_executionQueue, methodName, request, clientCapabilities, clientName, cancellationToken);
}
public async Task OpenDocumentAsync(Uri documentUri)
{
// LSP open files don't care about the project context, just the file contents with the URI.
// So pick any of the linked documents to get the text from.
var text = await TestWorkspace.CurrentSolution.GetDocuments(documentUri).First().GetTextAsync(CancellationToken.None).ConfigureAwait(false);
var didOpenParams = CreateDidOpenTextDocumentParams(documentUri, text.ToString());
await ExecuteRequestAsync<LSP.DidOpenTextDocumentParams, object>(LSP.Methods.TextDocumentDidOpenName,
didOpenParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task InsertTextAsync(Uri documentUri, params (int line, int column, string text)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (startLine: change.line, startColumn: change.column, endLine: change.line, endColumn: change.column, change.text)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None);
}
public Task DeleteTextAsync(Uri documentUri, params (int startLine, int startColumn, int endLine, int endColumn)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (change.startLine, change.startColumn, change.endLine, change.endColumn, text: string.Empty)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task CloseDocumentAsync(Uri documentUri)
{
var didCloseParams = CreateDidCloseTextDocumentParams(documentUri);
return ExecuteRequestAsync<LSP.DidCloseTextDocumentParams, object>(LSP.Methods.TextDocumentDidCloseName,
didCloseParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Solution GetCurrentSolution() => TestWorkspace.CurrentSolution;
internal RequestExecutionQueue.TestAccessor GetQueueAccessor() => _executionQueue.GetTestAccessor();
internal RequestDispatcher.TestAccessor GetDispatcherAccessor() => _requestDispatcher.GetTestAccessor();
public void Dispose()
{
TestWorkspace.Dispose();
_executionQueue.Shutdown();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Test;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Roslyn.Test.Utilities
{
[UseExportProvider]
public abstract class AbstractLanguageServerProtocolTests
{
// TODO: remove WPF dependency (IEditorInlineRenameService)
private static readonly TestComposition s_composition = EditorTestCompositions.LanguageServerProtocolWpf
.AddParts(typeof(TestLspWorkspaceRegistrationService))
.AddParts(typeof(TestDocumentTrackingService))
.AddParts(typeof(TestExperimentationService))
.RemoveParts(typeof(MockWorkspaceEventListenerProvider));
[Export(typeof(ILspWorkspaceRegistrationService)), PartNotDiscoverable]
internal class TestLspWorkspaceRegistrationService : ILspWorkspaceRegistrationService
{
private Workspace? _workspace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestLspWorkspaceRegistrationService()
{
}
public ImmutableArray<Workspace> GetAllRegistrations()
{
Contract.ThrowIfNull(_workspace, "No workspace has been registered");
return ImmutableArray.Create(_workspace);
}
public void Register(Workspace workspace)
{
Contract.ThrowIfTrue(_workspace != null);
_workspace = workspace;
}
}
private class TestSpanMapperProvider : IDocumentServiceProvider
{
TService IDocumentServiceProvider.GetService<TService>()
=> (TService)(object)new TestSpanMapper();
}
internal class TestSpanMapper : ISpanMappingService
{
private static readonly LinePositionSpan s_mappedLinePosition = new LinePositionSpan(new LinePosition(0, 0), new LinePosition(0, 5));
private static readonly string s_mappedFilePath = "c:\\MappedFile.cs";
internal static readonly string GeneratedFileName = "GeneratedFile.cs";
internal static readonly LSP.Location MappedFileLocation = new LSP.Location
{
Range = ProtocolConversions.LinePositionToRange(s_mappedLinePosition),
Uri = new Uri(s_mappedFilePath)
};
/// <summary>
/// LSP tests are simulating the new razor system which does support mapping import directives.
/// </summary>
public bool SupportsMappingImportDirectives => true;
public Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
ImmutableArray<MappedSpanResult> mappedResult = default;
if (document.Name == GeneratedFileName)
{
mappedResult = spans.Select(span => new MappedSpanResult(s_mappedFilePath, s_mappedLinePosition, new TextSpan(0, 5))).ToImmutableArray();
}
return Task.FromResult(mappedResult);
}
public Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync(
Document oldDocument,
Document newDocument,
CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
protected class OrderLocations : Comparer<LSP.Location>
{
public override int Compare(LSP.Location x, LSP.Location y) => CompareLocations(x, y);
}
protected virtual TestComposition Composition => s_composition;
/// <summary>
/// Asserts two objects are equivalent by converting to JSON and ignoring whitespace.
/// </summary>
/// <typeparam name="T">the JSON object type.</typeparam>
/// <param name="expected">the expected object to be converted to JSON.</param>
/// <param name="actual">the actual object to be converted to JSON.</param>
public static void AssertJsonEquals<T>(T expected, T actual)
{
var expectedStr = JsonConvert.SerializeObject(expected);
var actualStr = JsonConvert.SerializeObject(actual);
AssertEqualIgnoringWhitespace(expectedStr, actualStr);
}
protected static void AssertEqualIgnoringWhitespace(string expected, string actual)
{
var expectedWithoutWhitespace = Regex.Replace(expected, @"\s+", string.Empty);
var actualWithoutWhitespace = Regex.Replace(actual, @"\s+", string.Empty);
Assert.Equal(expectedWithoutWhitespace, actualWithoutWhitespace);
}
/// <summary>
/// Assert that two location lists are equivalent.
/// Locations are not always returned in a consistent order so they must be sorted.
/// </summary>
protected static void AssertLocationsEqual(IEnumerable<LSP.Location> expectedLocations, IEnumerable<LSP.Location> actualLocations)
{
var orderedActualLocations = actualLocations.OrderBy(CompareLocations);
var orderedExpectedLocations = expectedLocations.OrderBy(CompareLocations);
AssertJsonEquals(orderedExpectedLocations, orderedActualLocations);
}
protected static int CompareLocations(LSP.Location l1, LSP.Location l2)
{
var compareDocument = l1.Uri.OriginalString.CompareTo(l2.Uri.OriginalString);
var compareRange = CompareRange(l1.Range, l2.Range);
return compareDocument != 0 ? compareDocument : compareRange;
}
protected static int CompareRange(LSP.Range r1, LSP.Range r2)
{
var compareLine = r1.Start.Line.CompareTo(r2.Start.Line);
var compareChar = r1.Start.Character.CompareTo(r2.Start.Character);
return compareLine != 0 ? compareLine : compareChar;
}
protected static string ApplyTextEdits(LSP.TextEdit[] edits, SourceText originalMarkup)
{
var text = originalMarkup;
foreach (var edit in edits)
{
var lines = text.Lines;
var startPosition = ProtocolConversions.PositionToLinePosition(edit.Range.Start);
var endPosition = ProtocolConversions.PositionToLinePosition(edit.Range.End);
var textSpan = lines.GetTextSpan(new LinePositionSpan(startPosition, endPosition));
text = text.Replace(textSpan, edit.NewText);
}
return text.ToString();
}
internal static LSP.SymbolInformation CreateSymbolInformation(LSP.SymbolKind kind, string name, LSP.Location location, Glyph glyph, string? containerName = null)
{
var info = new LSP.VSSymbolInformation()
{
Kind = kind,
Name = name,
Location = location,
Icon = new ImageElement(glyph.GetImageId()),
};
if (containerName != null)
{
info.ContainerName = containerName;
}
return info;
}
protected static LSP.TextDocumentIdentifier CreateTextDocumentIdentifier(Uri uri, ProjectId? projectContext = null)
{
var documentIdentifier = new LSP.VSTextDocumentIdentifier { Uri = uri };
if (projectContext != null)
{
documentIdentifier.ProjectContext =
new LSP.ProjectContext { Id = ProtocolConversions.ProjectIdToProjectContextId(projectContext) };
}
return documentIdentifier;
}
protected static LSP.TextDocumentPositionParams CreateTextDocumentPositionParams(LSP.Location caret, ProjectId? projectContext = null)
=> new LSP.TextDocumentPositionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri, projectContext),
Position = caret.Range.Start
};
protected static LSP.MarkupContent CreateMarkupContent(LSP.MarkupKind kind, string value)
=> new LSP.MarkupContent()
{
Kind = kind,
Value = value
};
protected static LSP.CompletionParams CreateCompletionParams(
LSP.Location caret,
LSP.VSCompletionInvokeKind invokeKind,
string triggerCharacter,
LSP.CompletionTriggerKind triggerKind)
=> new LSP.CompletionParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.VSCompletionContext()
{
InvokeKind = invokeKind,
TriggerCharacter = triggerCharacter,
TriggerKind = triggerKind,
}
};
protected static async Task<LSP.VSCompletionItem> CreateCompletionItemAsync(
string label,
LSP.CompletionItemKind kind,
string[] tags,
LSP.CompletionParams request,
Document document,
bool preselect = false,
ImmutableArray<char>? commitCharacters = null,
LSP.TextEdit? textEdit = null,
string? insertText = null,
string? sortText = null,
string? filterText = null,
long resultId = 0)
{
var position = await document.GetPositionFromLinePositionAsync(
ProtocolConversions.PositionToLinePosition(request.Position), CancellationToken.None).ConfigureAwait(false);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(
request.Context, document, position, CancellationToken.None).ConfigureAwait(false);
var item = new LSP.VSCompletionItem()
{
TextEdit = textEdit,
InsertText = insertText,
FilterText = filterText ?? label,
Label = label,
SortText = sortText ?? label,
InsertTextFormat = LSP.InsertTextFormat.Plaintext,
Kind = kind,
Data = JObject.FromObject(new CompletionResolveData()
{
ResultId = resultId,
}),
Preselect = preselect
};
if (tags != null)
item.Icon = tags.ToImmutableArray().GetFirstGlyph().GetImageElement();
if (commitCharacters != null)
item.CommitCharacters = commitCharacters.Value.Select(c => c.ToString()).ToArray();
return item;
}
protected static LSP.TextEdit GenerateTextEdit(string newText, int startLine, int startChar, int endLine, int endChar)
=> new LSP.TextEdit
{
NewText = newText,
Range = new LSP.Range
{
Start = new LSP.Position { Line = startLine, Character = startChar },
End = new LSP.Position { Line = endLine, Character = endChar }
}
};
private protected static CodeActionResolveData CreateCodeActionResolveData(string uniqueIdentifier, LSP.Location location, IEnumerable<string>? customTags = null)
=> new CodeActionResolveData(uniqueIdentifier, customTags.ToImmutableArrayOrEmpty(), location.Range, CreateTextDocumentIdentifier(location.Uri));
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the markup.
/// </summary>
protected TestLspServer CreateTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.CSharp);
protected TestLspServer CreateVisualBasicTestLspServer(string markup, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(new string[] { markup }, out locations, LanguageNames.VisualBasic);
/// <summary>
/// Creates an LSP server backed by a workspace instance with a solution containing the specified documents.
/// </summary>
protected TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations)
=> CreateTestLspServer(markups, out locations, LanguageNames.CSharp);
private TestLspServer CreateTestLspServer(string[] markups, out Dictionary<string, IList<LSP.Location>> locations, string languageName)
{
var workspace = languageName switch
{
LanguageNames.CSharp => TestWorkspace.CreateCSharp(markups, composition: Composition),
LanguageNames.VisualBasic => TestWorkspace.CreateVisualBasic(markups, composition: Composition),
_ => throw new ArgumentException($"language name {languageName} is not valid for a test workspace"),
};
RegisterWorkspaceForLsp(workspace);
var solution = workspace.CurrentSolution;
foreach (var document in workspace.Documents)
{
solution = solution.WithDocumentFilePath(document.Id, GetDocumentFilePathFromName(document.Name));
}
workspace.ChangeSolution(solution);
locations = GetAnnotatedLocations(workspace, solution);
return new TestLspServer(workspace);
}
protected TestLspServer CreateXmlTestLspServer(string xmlContent, out Dictionary<string, IList<LSP.Location>> locations)
{
var workspace = TestWorkspace.Create(xmlContent, composition: Composition);
RegisterWorkspaceForLsp(workspace);
locations = GetAnnotatedLocations(workspace, workspace.CurrentSolution);
return new TestLspServer(workspace);
}
protected static void AddMappedDocument(Workspace workspace, string markup)
{
var generatedDocumentId = DocumentId.CreateNewId(workspace.CurrentSolution.ProjectIds.First());
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(SourceText.From(markup), version, TestSpanMapper.GeneratedFileName));
var generatedDocumentInfo = DocumentInfo.Create(generatedDocumentId, TestSpanMapper.GeneratedFileName, SpecializedCollections.EmptyReadOnlyList<string>(),
SourceCodeKind.Regular, loader, $"C:\\{TestSpanMapper.GeneratedFileName}", isGenerated: true, designTimeOnly: false, new TestSpanMapperProvider());
var newSolution = workspace.CurrentSolution.AddDocument(generatedDocumentInfo);
workspace.TryApplyChanges(newSolution);
}
private protected static void RegisterWorkspaceForLsp(TestWorkspace workspace)
{
var provider = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
provider.Register(workspace);
}
public static Dictionary<string, IList<LSP.Location>> GetAnnotatedLocations(TestWorkspace workspace, Solution solution)
{
var locations = new Dictionary<string, IList<LSP.Location>>();
foreach (var testDocument in workspace.Documents)
{
var document = solution.GetRequiredDocument(testDocument.Id);
var text = document.GetTextSynchronously(CancellationToken.None);
foreach (var (name, spans) in testDocument.AnnotatedSpans)
{
var locationsForName = locations.GetValueOrDefault(name, new List<LSP.Location>());
locationsForName.AddRange(spans.Select(span => ConvertTextSpanWithTextToLocation(span, text, new Uri(document.FilePath))));
// Linked files will return duplicate annotated Locations for each document that links to the same file.
// Since the test output only cares about the actual file, make sure we de-dupe before returning.
locations[name] = locationsForName.Distinct().ToList();
}
}
return locations;
static LSP.Location ConvertTextSpanWithTextToLocation(TextSpan span, SourceText text, Uri documentUri)
{
var location = new LSP.Location
{
Uri = documentUri,
Range = ProtocolConversions.TextSpanToRange(span, text),
};
return location;
}
}
private static RequestDispatcher CreateRequestDispatcher(TestWorkspace workspace)
{
var factory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>();
return factory.CreateRequestDispatcher();
}
private static RequestExecutionQueue CreateRequestQueue(TestWorkspace workspace)
{
var registrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
return new RequestExecutionQueue(NoOpLspLogger.Instance, registrationService, serverName: "Tests", "TestClient");
}
private static string GetDocumentFilePathFromName(string documentName)
=> "C:\\" + documentName;
private static LSP.DidChangeTextDocumentParams CreateDidChangeTextDocumentParams(
Uri documentUri,
ImmutableArray<(int startLine, int startColumn, int endLine, int endColumn, string text)> changes)
{
var changeEvents = changes.Select(change => new LSP.TextDocumentContentChangeEvent
{
Text = change.text,
Range = new LSP.Range
{
Start = new LSP.Position(change.startLine, change.startColumn),
End = new LSP.Position(change.endLine, change.endColumn)
}
}).ToArray();
return new LSP.DidChangeTextDocumentParams()
{
TextDocument = new LSP.VersionedTextDocumentIdentifier
{
Uri = documentUri
},
ContentChanges = changeEvents
};
}
private static LSP.DidOpenTextDocumentParams CreateDidOpenTextDocumentParams(Uri uri, string source)
=> new LSP.DidOpenTextDocumentParams
{
TextDocument = new LSP.TextDocumentItem
{
Text = source,
Uri = uri
}
};
private static LSP.DidCloseTextDocumentParams CreateDidCloseTextDocumentParams(Uri uri)
=> new LSP.DidCloseTextDocumentParams()
{
TextDocument = new LSP.TextDocumentIdentifier
{
Uri = uri
}
};
public sealed class TestLspServer : IDisposable
{
public readonly TestWorkspace TestWorkspace;
private readonly RequestDispatcher _requestDispatcher;
private readonly RequestExecutionQueue _executionQueue;
internal TestLspServer(TestWorkspace testWorkspace)
{
TestWorkspace = testWorkspace;
_requestDispatcher = CreateRequestDispatcher(testWorkspace);
_executionQueue = CreateRequestQueue(testWorkspace);
}
public Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(string methodName, RequestType request, LSP.ClientCapabilities clientCapabilities,
string? clientName, CancellationToken cancellationToken) where RequestType : class
{
return _requestDispatcher.ExecuteRequestAsync<RequestType, ResponseType>(
_executionQueue, methodName, request, clientCapabilities, clientName, cancellationToken);
}
public async Task OpenDocumentAsync(Uri documentUri)
{
// LSP open files don't care about the project context, just the file contents with the URI.
// So pick any of the linked documents to get the text from.
var text = await TestWorkspace.CurrentSolution.GetDocuments(documentUri).First().GetTextAsync(CancellationToken.None).ConfigureAwait(false);
var didOpenParams = CreateDidOpenTextDocumentParams(documentUri, text.ToString());
await ExecuteRequestAsync<LSP.DidOpenTextDocumentParams, object>(LSP.Methods.TextDocumentDidOpenName,
didOpenParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task InsertTextAsync(Uri documentUri, params (int line, int column, string text)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (startLine: change.line, startColumn: change.column, endLine: change.line, endColumn: change.column, change.text)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), clientName: null, CancellationToken.None);
}
public Task DeleteTextAsync(Uri documentUri, params (int startLine, int startColumn, int endLine, int endColumn)[] changes)
{
var didChangeParams = CreateDidChangeTextDocumentParams(
documentUri,
changes.Select(change => (change.startLine, change.startColumn, change.endLine, change.endColumn, text: string.Empty)).ToImmutableArray());
return ExecuteRequestAsync<LSP.DidChangeTextDocumentParams, object>(LSP.Methods.TextDocumentDidChangeName,
didChangeParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Task CloseDocumentAsync(Uri documentUri)
{
var didCloseParams = CreateDidCloseTextDocumentParams(documentUri);
return ExecuteRequestAsync<LSP.DidCloseTextDocumentParams, object>(LSP.Methods.TextDocumentDidCloseName,
didCloseParams, new LSP.ClientCapabilities(), null, CancellationToken.None);
}
public Solution GetCurrentSolution() => TestWorkspace.CurrentSolution;
internal RequestExecutionQueue.TestAccessor GetQueueAccessor() => _executionQueue.GetTestAccessor();
internal RequestDispatcher.TestAccessor GetDispatcherAccessor() => _requestDispatcher.GetTestAccessor();
public void Dispose()
{
TestWorkspace.Dispose();
_executionQueue.Shutdown();
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Binder/Binder.NamespaceOrTypeOrAliasSymbolWithAnnotations.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
internal readonly struct NamespaceOrTypeOrAliasSymbolWithAnnotations
{
private readonly TypeWithAnnotations _typeWithAnnotations;
private readonly Symbol _symbol;
private readonly bool _isNullableEnabled;
private NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations typeWithAnnotations)
{
Debug.Assert(typeWithAnnotations.HasType);
_typeWithAnnotations = typeWithAnnotations;
_symbol = null;
_isNullableEnabled = false; // Not meaningful for a TypeWithAnnotations, it already baked the fact into its content.
}
private NamespaceOrTypeOrAliasSymbolWithAnnotations(Symbol symbol, bool isNullableEnabled)
{
Debug.Assert(!(symbol is TypeSymbol));
_typeWithAnnotations = default;
_symbol = symbol;
_isNullableEnabled = isNullableEnabled;
}
internal TypeWithAnnotations TypeWithAnnotations => _typeWithAnnotations;
internal Symbol Symbol => _symbol ?? TypeWithAnnotations.Type;
internal bool IsType => !_typeWithAnnotations.IsDefault;
internal bool IsAlias => _symbol?.Kind == SymbolKind.Alias;
internal NamespaceOrTypeSymbol NamespaceOrTypeSymbol => Symbol as NamespaceOrTypeSymbol;
internal bool IsDefault => !_typeWithAnnotations.HasType && _symbol is null;
internal bool IsNullableEnabled
{
get
{
Debug.Assert(_symbol?.Kind == SymbolKind.Alias); // Not meaningful to use this property otherwise
return _isNullableEnabled;
}
}
internal static NamespaceOrTypeOrAliasSymbolWithAnnotations CreateUnannotated(bool isNullableEnabled, Symbol symbol)
{
if (symbol is null)
{
return default;
}
var type = symbol as TypeSymbol;
return type is null ?
new NamespaceOrTypeOrAliasSymbolWithAnnotations(symbol, isNullableEnabled) :
new NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations.Create(isNullableEnabled, type));
}
public static implicit operator NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations typeWithAnnotations)
{
return new NamespaceOrTypeOrAliasSymbolWithAnnotations(typeWithAnnotations);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
internal readonly struct NamespaceOrTypeOrAliasSymbolWithAnnotations
{
private readonly TypeWithAnnotations _typeWithAnnotations;
private readonly Symbol _symbol;
private readonly bool _isNullableEnabled;
private NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations typeWithAnnotations)
{
Debug.Assert(typeWithAnnotations.HasType);
_typeWithAnnotations = typeWithAnnotations;
_symbol = null;
_isNullableEnabled = false; // Not meaningful for a TypeWithAnnotations, it already baked the fact into its content.
}
private NamespaceOrTypeOrAliasSymbolWithAnnotations(Symbol symbol, bool isNullableEnabled)
{
Debug.Assert(!(symbol is TypeSymbol));
_typeWithAnnotations = default;
_symbol = symbol;
_isNullableEnabled = isNullableEnabled;
}
internal TypeWithAnnotations TypeWithAnnotations => _typeWithAnnotations;
internal Symbol Symbol => _symbol ?? TypeWithAnnotations.Type;
internal bool IsType => !_typeWithAnnotations.IsDefault;
internal bool IsAlias => _symbol?.Kind == SymbolKind.Alias;
internal NamespaceOrTypeSymbol NamespaceOrTypeSymbol => Symbol as NamespaceOrTypeSymbol;
internal bool IsDefault => !_typeWithAnnotations.HasType && _symbol is null;
internal bool IsNullableEnabled
{
get
{
Debug.Assert(_symbol?.Kind == SymbolKind.Alias); // Not meaningful to use this property otherwise
return _isNullableEnabled;
}
}
internal static NamespaceOrTypeOrAliasSymbolWithAnnotations CreateUnannotated(bool isNullableEnabled, Symbol symbol)
{
if (symbol is null)
{
return default;
}
var type = symbol as TypeSymbol;
return type is null ?
new NamespaceOrTypeOrAliasSymbolWithAnnotations(symbol, isNullableEnabled) :
new NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations.Create(isNullableEnabled, type));
}
public static implicit operator NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeWithAnnotations typeWithAnnotations)
{
return new NamespaceOrTypeOrAliasSymbolWithAnnotations(typeWithAnnotations);
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Diagnostics/WorkspaceAnalyzerOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Host;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Analyzer options with workspace.
/// These are used to fetch the workspace options by our internal analyzers (e.g. simplification analyzer).
/// </summary>
internal sealed class WorkspaceAnalyzerOptions : AnalyzerOptions
{
private readonly Solution _solution;
public WorkspaceAnalyzerOptions(AnalyzerOptions options, Solution solution)
: base(options.AdditionalFiles, options.AnalyzerConfigOptionsProvider)
{
_solution = solution;
}
public HostWorkspaceServices Services => _solution.Workspace.Services;
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<OptionSet> GetDocumentOptionSetAsync(SyntaxTree syntaxTree, CancellationToken cancellationToken)
{
var documentId = _solution.GetDocumentId(syntaxTree);
if (documentId == null)
{
return _solution.Options;
}
var document = _solution.GetDocument(documentId);
if (document == null)
{
return _solution.Options;
}
return await document.GetOptionsAsync(_solution.Options, cancellationToken).ConfigureAwait(false);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
return obj is WorkspaceAnalyzerOptions other &&
_solution.WorkspaceVersion == other._solution.WorkspaceVersion &&
_solution.Workspace == other._solution.Workspace &&
base.Equals(other);
}
public override int GetHashCode()
{
return Hash.Combine(_solution.Workspace,
Hash.Combine(_solution.WorkspaceVersion, base.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.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Analyzer options with workspace.
/// These are used to fetch the workspace options by our internal analyzers (e.g. simplification analyzer).
/// </summary>
internal sealed class WorkspaceAnalyzerOptions : AnalyzerOptions
{
private readonly Solution _solution;
public WorkspaceAnalyzerOptions(AnalyzerOptions options, Solution solution)
: base(options.AdditionalFiles, options.AnalyzerConfigOptionsProvider)
{
_solution = solution;
}
public HostWorkspaceServices Services => _solution.Workspace.Services;
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<OptionSet> GetDocumentOptionSetAsync(SyntaxTree syntaxTree, CancellationToken cancellationToken)
{
var documentId = _solution.GetDocumentId(syntaxTree);
if (documentId == null)
{
return _solution.Options;
}
var document = _solution.GetDocument(documentId);
if (document == null)
{
return _solution.Options;
}
return await document.GetOptionsAsync(_solution.Options, cancellationToken).ConfigureAwait(false);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
return obj is WorkspaceAnalyzerOptions other &&
_solution.WorkspaceVersion == other._solution.WorkspaceVersion &&
_solution.Workspace == other._solution.Workspace &&
base.Equals(other);
}
public override int GetHashCode()
{
return Hash.Combine(_solution.Workspace,
Hash.Combine(_solution.WorkspaceVersion, base.GetHashCode()));
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/View/CodeStyleSeverityControl.xaml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Windows.Automation;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleSeverityControl.xaml
/// </summary>
internal partial class CodeStyleSeverityControl : UserControl
{
private readonly ComboBox _comboBox;
private readonly CodeStyleSetting _setting;
public CodeStyleSeverityControl(CodeStyleSetting setting)
{
InitializeComponent();
_setting = setting;
_comboBox = new ComboBox()
{
ItemsSource = new[]
{
ServicesVSResources.Refactoring_Only,
ServicesVSResources.Suggestion,
ServicesVSResources.Warning,
ServicesVSResources.Error
}
};
_comboBox.SelectedIndex = setting.Severity switch
{
DiagnosticSeverity.Hidden => 0,
DiagnosticSeverity.Info => 1,
DiagnosticSeverity.Warning => 2,
DiagnosticSeverity.Error => 3,
_ => throw new InvalidOperationException(),
};
_comboBox.SelectionChanged += ComboBox_SelectionChanged;
_comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity);
_ = RootGrid.Children.Add(_comboBox);
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var severity = _comboBox.SelectedIndex switch
{
0 => DiagnosticSeverity.Hidden,
1 => DiagnosticSeverity.Info,
2 => DiagnosticSeverity.Warning,
3 => DiagnosticSeverity.Error,
_ => throw new InvalidOperationException(),
};
if (_setting.Severity != severity)
{
_setting.ChangeSeverity(severity);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Windows.Automation;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleSeverityControl.xaml
/// </summary>
internal partial class CodeStyleSeverityControl : UserControl
{
private readonly ComboBox _comboBox;
private readonly CodeStyleSetting _setting;
public CodeStyleSeverityControl(CodeStyleSetting setting)
{
InitializeComponent();
_setting = setting;
_comboBox = new ComboBox()
{
ItemsSource = new[]
{
ServicesVSResources.Refactoring_Only,
ServicesVSResources.Suggestion,
ServicesVSResources.Warning,
ServicesVSResources.Error
}
};
_comboBox.SelectedIndex = setting.Severity switch
{
DiagnosticSeverity.Hidden => 0,
DiagnosticSeverity.Info => 1,
DiagnosticSeverity.Warning => 2,
DiagnosticSeverity.Error => 3,
_ => throw new InvalidOperationException(),
};
_comboBox.SelectionChanged += ComboBox_SelectionChanged;
_comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity);
_ = RootGrid.Children.Add(_comboBox);
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var severity = _comboBox.SelectedIndex switch
{
0 => DiagnosticSeverity.Hidden,
1 => DiagnosticSeverity.Info,
2 => DiagnosticSeverity.Warning,
3 => DiagnosticSeverity.Error,
_ => throw new InvalidOperationException(),
};
if (_setting.Severity != severity)
{
_setting.ChangeSeverity(severity);
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ICollectionExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class ICollectionExtensions
{
public static void RemoveRange<T>(this ICollection<T> collection, IEnumerable<T>? items)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if (items != null)
{
foreach (var item in items)
{
collection.Remove(item);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class ICollectionExtensions
{
public static void RemoveRange<T>(this ICollection<T> collection, IEnumerable<T>? items)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if (items != null)
{
foreach (var item in items)
{
collection.Remove(item);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/SourceGeneration/ISourceGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The base interface required to implement a source generator
/// </summary>
/// <remarks>
/// The lifetime of a generator is controlled by the compiler.
/// State should not be stored directly on the generator, as there
/// is no guarantee that the same instance will be used on a
/// subsequent generation pass.
/// </remarks>
public interface ISourceGenerator
{
/// <summary>
/// Called before generation occurs. A generator can use the <paramref name="context"/>
/// to register callbacks required to perform generation.
/// </summary>
/// <param name="context">The <see cref="GeneratorInitializationContext"/> to register callbacks on</param>
void Initialize(GeneratorInitializationContext context);
/// <summary>
/// Called to perform source generation. A generator can use the <paramref name="context"/>
/// to add source files via the <see cref="GeneratorExecutionContext.AddSource(string, SourceText)"/>
/// method.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> to add source to</param>
/// <remarks>
/// This call represents the main generation step. It is called after a <see cref="Compilation"/> is
/// created that contains the user written code.
///
/// A generator can use the <see cref="GeneratorExecutionContext.Compilation"/> property to
/// discover information about the users compilation and make decisions on what source to
/// provide.
/// </remarks>
void Execute(GeneratorExecutionContext context);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The base interface required to implement a source generator
/// </summary>
/// <remarks>
/// The lifetime of a generator is controlled by the compiler.
/// State should not be stored directly on the generator, as there
/// is no guarantee that the same instance will be used on a
/// subsequent generation pass.
/// </remarks>
public interface ISourceGenerator
{
/// <summary>
/// Called before generation occurs. A generator can use the <paramref name="context"/>
/// to register callbacks required to perform generation.
/// </summary>
/// <param name="context">The <see cref="GeneratorInitializationContext"/> to register callbacks on</param>
void Initialize(GeneratorInitializationContext context);
/// <summary>
/// Called to perform source generation. A generator can use the <paramref name="context"/>
/// to add source files via the <see cref="GeneratorExecutionContext.AddSource(string, SourceText)"/>
/// method.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> to add source to</param>
/// <remarks>
/// This call represents the main generation step. It is called after a <see cref="Compilation"/> is
/// created that contains the user written code.
///
/// A generator can use the <see cref="GeneratorExecutionContext.Compilation"/> property to
/// discover information about the users compilation and make decisions on what source to
/// provide.
/// </remarks>
void Execute(GeneratorExecutionContext context);
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Completion/MatchPriority.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Completion
{
/// <summary>
/// An additional hint to the matching algorithm that can
/// augment or override the existing text-based matching.
/// </summary>
public static class MatchPriority
{
/// <summary>
/// The matching algorithm should give this item no special treatment.
///
/// Ordinary <see cref="CompletionProvider"/>s typically specify this.
/// </summary>
public static readonly int Default = 0;
/// <summary>
/// The matching algorithm will tend to prefer this item unless
/// a dramatically better text-based match is available.
///
/// With no filter text, this item (or the first item alphabetically
/// with this priority) should always be selected.
///
/// This is used for specific IDE scenarios like "Object creation preselection"
/// or "Enum preselection" or "Completion list tag preselection".
/// </summary>
public static readonly int Preselect = int.MaxValue / 2;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// An additional hint to the matching algorithm that can
/// augment or override the existing text-based matching.
/// </summary>
public static class MatchPriority
{
/// <summary>
/// The matching algorithm should give this item no special treatment.
///
/// Ordinary <see cref="CompletionProvider"/>s typically specify this.
/// </summary>
public static readonly int Default = 0;
/// <summary>
/// The matching algorithm will tend to prefer this item unless
/// a dramatically better text-based match is available.
///
/// With no filter text, this item (or the first item alphabetically
/// with this priority) should always be selected.
///
/// This is used for specific IDE scenarios like "Object creation preselection"
/// or "Enum preselection" or "Completion list tag preselection".
/// </summary>
public static readonly int Preselect = int.MaxValue / 2;
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Shared/TestHooks/IAsyncToken.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
internal interface IAsyncToken : IDisposable
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
internal interface IAsyncToken : IDisposable
{
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/ExtractMethod/SelectionValidatorTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod
{
public class SelectionValidatorTests : ExtractMethodBase
{
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest1()
{
var code = "{|b:using System;|}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest2()
{
var code = @"{|b:namespace A|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest3()
{
var code = @"namespace {|b:A|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest4()
{
var code = @"{|b:class|} A
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest5()
{
var code = @"class {|b:A|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest6()
{
var code = @"class A : {|b:object|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest7()
{
var code = @"class A : object, {|b:IDisposable|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest8()
{
var code = @"class A<{|b:T|}>
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest9()
{
var code = @"class A<T> where {|b:T|} : class
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest10()
{
var code = @"class A<T> where T : {|b:IDisposable|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest11()
{
var code = @"class A
{
{|b:A|} Method()
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest12()
{
var code = @"class A
{
A Method({|b:A|} a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest13()
{
var code = @"class A
{
A Method(A {|b:a|})
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest14()
{
var code = @"class A
{
[{|b:Goo|}]
A Method(A a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest15()
{
var code = @"class A
{
[Goo({|b:A|}=1)]
A Method(A a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest16()
{
var code = @"class A
{
[Goo(A={|b:1|})]
A Method(A a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest17()
{
var code = @"class A
{
const int {|b:i|} = 1;
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest18()
{
var code = @"class A
{
const {|b:int|} i = 1;
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest19()
{
var code = @"class A
{
const int i = {|b:1|};
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest20()
{
var code = @"class A
{
const int i = {|r:{|b:1 + |}2|};
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest21()
{
var code = @"class A
{
const int {|b:i = 1 + |}2;
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest22()
{
var code = @"class A
{
void Method1()
{
{|b:int i = 1;
}
void Method2()
{
int b = 2;|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest23()
{
var code = @"class A
{
void Method1()
{
{|b:int i = 1;
}|}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest24()
{
var code = @"class A
{
void Method1()
{
#region A
{|b:int i = 1;|}
#endRegion
}
}";
await TestSelectionAsync(code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest25()
{
var code = @"class A
{
void Method1()
{
{|b:#region A
int i = 1;|}
#endRegion
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest26()
{
var code = @"class A
{
void Method1()
{
#region A
{|b:int i = 1;
#endregion|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest27()
{
var code = @"class A
{
void Method1()
{
#region A
{|b:#endregion
int i = 1;|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest28()
{
var code = @"class A
{
void Method1()
{
#if true
{|b:int i = 1;
#endif|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest29()
{
var code = @"class A
{
void Method1()
{
{|b:#if true
int i = 1;|}
#endif
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest30()
{
var code = @"class A
{
void Method1()
{
#if true
{|b:#endif
int i = 1;|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest31()
{
var code = @"class A
{
void Method1()
{
#if false
{|b:#else
int i = 1;|}
#endif
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest32()
{
var code = @"class A
{
void Method1()
{
#if false
{|b:#elsif true
int i = 1;|}
#endif
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest33()
{
var code = @"class A
{
void Method1()
{
{|b:#if true
int i = 1;
#endif|}
}
}";
await TestSelectionAsync(code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest34()
{
var code = @"class A
{
void Method1()
{
{|b:#region
int i = 1;
#endregion|}
}
}";
await TestSelectionAsync(code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest35()
{
var code = @"class A
{
void Method1()
{
{|b:// test|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest36()
{
var code = @"class A
{
IEnumerable<int> Method1()
{
{|r:{|b:yield return 1;|}|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest37()
{
var code = @"class A
{
void Method1()
{
try
{
}
catch
{
{|b:throw;|}
}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest38()
{
var code = @"class A
{
void Method1()
{
try
{
}
catch
{
{|b:throw new Exception();|}
}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest39()
{
var code = @"class A
{
void Method1()
{
{|r:{|b:System|}.Console.WriteLine(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest40()
{
var code = @"class A
{
void Method1()
{
{|r:{|b:System.Console|}.WriteLine(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest41()
{
var code = @"class A
{
void Method1()
{
{|r:{|b:System.Console.WriteLine|}(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest42()
{
var code = @"class A
{
void Method1()
{
{|r: System.{|b:Console|}.WriteLine(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest43()
{
var code = @"class A
{
void Method1()
{
{|r: System.{|b:Console.WriteLine|}(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest44()
{
var code = @"class A
{
void Method1()
{
{|r: System.Console.{|b:WriteLine|}(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(539242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539242")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest45()
{
var code = @"class A
{
void Method1()
{
short[,] arr = {|r:new short[,] { {|b:{ 19, 19, 19 }|}, { 19, 19, 19 } }|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(539242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539242")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest46()
{
var code = @"class A
{
void Method1()
{
short[,] arr = {|r:{ {|b:{ 19, 19, 19 }|}, { 19, 19, 19 } }|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540338")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest47()
{
var code = @"using System;
class C
{
void M()
{
Action<string> d = s => Console.Write(s);
{|b:d +=|}
}
}
";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectIfWithReturn()
{
var code = @"class A
{
public void Method1()
{
bool b = true;
{|b:if (b)
return;|}
return;
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectConstIfWithReturn()
{
var code = @"class A
{
public void Method1()
{
const bool b = true;
{|b:if (b)
return;|}
Console.WriteLine();
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectReturnButNotAllCodePathsContainAReturn()
{
var code = @"class A
{
public void Method1(bool b1, bool b2)
{
if (b1)
{
{|b:if (b2)
return;
Console.WriteLine();|}
}
Console.WriteLine();
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectIfBranchWhereNotAllPathsReturn()
{
var code = @"class A
{
int Method8(int i)
{
{|b:if (i > 100)
{
return i++;
}
else if (i > 90)
{
return i--;
}
else
{
i++;
}|}
return i;
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCatchFilterClause()
{
var code = @"class A
{
int method()
{
try
{
Console.Write(5);
}
catch (Exception ex) if ({|b:ex.Message == ""goo""|})
{
throw;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCatchFilterClause2()
{
var code = @"class A
{
int method()
{
int i = 5;
try
{
Console.Write(5);
}
catch (Exception ex) if ({|b:i == 5|})
{
Console.Write(5);
i = 0;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectWithinCatchFilterClause()
{
var code = @"class A
{
int method()
{
try
{
Console.Write(5);
}
catch (Exception ex) if ({|b:ex.Message|} == ""goo"")
{
throw;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectWithinCatchFilterClause2()
{
var code = @"class A
{
int method()
{
try
{
Console.Write(5);
}
catch (Exception ex) if (ex.Message == {|b:""goo""|})
{
throw;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLValueOfPlusEqualsOperator()
{
var code = @"class A
{
int method()
{
int i = 0;
{|r:{|b:i|} += 1;|}
return i;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectRValueOfPlusEqualsOperator()
{
var code = @"class A
{
int method()
{
int i = 0;
i += {|b:1|};
return i;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectRValueOfPredecrementOperator()
{
var code = @"class A
{
string method(string s, int i)
{
string[] myvar = new string[i];
myvar[0] = s;
myvar[{|r:--{|b:i|}|}] = s + i.ToString();
return myvar[i];
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectArrayWithDecrementIndex()
{
var code = @"class A
{
string method(string s, int i)
{
string[] myvar = new string[i];
myvar[0] = s;
{|r:{|b:myvar[--i]|} = s + i.ToString();|}
return myvar[i];
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCastOperator()
{
var code = @"class A
{
int method(string goo)
{
String bar = {|b:(String)goo|};
return bar.Length;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLHSOfPostIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:i|}++|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectPostIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:i{|b:++|}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectRHSOfPreIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:++|}i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectPreIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:++|}i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectPreDecrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:--|}i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLHSOfPostDecrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:i|}--|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectUnaryPlusOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:+|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectUnaryMinusOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:-|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLogicalNegationOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:!|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectBitwiseNegationOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:~|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCastOperator2()
{
var code = @"class A
{
int method(double i)
{
int j = {|r:{|b:(int)|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectInvalidSubexpressionToExpand()
{
var code = @"class A
{
public int method(int a, int b, int c)
{
return {|r:a + {|b:b + c|}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectValidSubexpressionAndHenceDontExpand()
{
var code = @"class A
{
public int method(int a, int b, int c)
{
return {|b:a + b|} + c;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLHSOfMinusEqualsOperator()
{
var code = @"class A
{
public int method(int a, int b)
{
{|r:{|b:a|} -= b;|}
return a;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectInnerBlockPartially()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
ArrayList ar = null;
foreach (object var in ar)
{
{|r:{|b:System.Console.WriteLine();
foreach (object var2 in ar)
{
System.Console.WriteLine();|}
}|}
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectInnerBlockWithoutBracesPartially()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
while (true)
{
int i = 0;
{|r: if (i == 0)
Console.WriteLine(){|b:;
Console.WriteLine();|}|}
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectBeginningBrace()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
if (true) {|r:{|b:{|} }|}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectAcrossBlocks1()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
if (true)
{
{|r: for (int i = 0; i < 100; i++)
{
{|b:System.Console.WriteLine();
}
System.Console.WriteLine();|}|}
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectMethodParameters()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
double x1 = 10;
double y1 = 20;
double z1 = 30;
double ret = {|r:sum({|b:ref x1, y1, z1|})|};
}
double sum(ref double x, double y, double z)
{
x++;
return x + y + z;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectChainedInvocations1()
{
var code = @"using System;
using System.Collections;
class Test
{
class B
{
public int c()
{
return 100;
}
}
class A
{
public B b = new B();
}
void method()
{
A a = new A();
{|b:a.b|}.c();
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectChainedInvocations2()
{
var code = @"using System;
using System.Collections;
class Test
{
class B
{
public int c()
{
return 100;
}
}
class A
{
public B b = new B();
}
void method()
{
A a = new A();
{|r: a.{|b:b.c()|}|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540474")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task GotoStatement()
{
var code = @"using System;
using System.Reflection.Emit;
class Program
{
public delegate R Del<in T, out R>(T arg);
static void Main(string[] args)
{
Del<ArgumentException, Exception> del = {|r:(arg) =>
{
goto {|b:Label|};
Label:
return new ArgumentException();
}|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540481")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task BugFix6750()
{
var code = @"using System;
class Program
{
int[] array = new int[{|b:1|}];
}";
await TestSelectionAsync(code);
}
[WorkItem(540481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540481")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task BugFix6750_1()
{
var code = @"using System;
class Program
{
int[] array = {|r:new int[{|b:1|}] { 1 }|};
}";
await TestSelectionAsync(code);
}
[WorkItem(542201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542201")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task MalformedCode_NoOuterType()
{
var code = @"x(a){
{|b:for ();|}
}
";
await TestSelectionAsync(code, expectedFail: true);
}
[WorkItem(542210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542210")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NoQueryContinuation()
{
var code = @"using System.Linq;
class P
{
static void Main()
{
var src = new int[] { 4, 5 };
var q = {|r:from x in src
select x into y
{|b:select y|}|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540787")]
[WorkItem(542722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542722")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task DontCrash()
=> await IterateAllAsync(TestResource.AllInOneCSharpCode);
[WorkItem(9931, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task ExtractMethodIdentifierAtEndOfInteractiveBuffer()
{
var code = @"using System.Console;
WriteLine();
{|r:{|b:Diagnostic|}|}";
await TestSelectionAsync(code, expectedFail: true);
}
[WorkItem(543020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543020")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task MemberAccessStructAsExpression()
{
var code = @"struct S
{
public float X;
public float Y;
public float Z;
void M()
{
if (3 < 3.4)
{
S s;
if (s.X < 3)
{
s = GetS();
{|r:{|b:s|}.Z = 10f;|}
}
else
{
}
}
else
{
}
}
private static S GetS()
{
return new S();
}
} ";
await TestSelectionAsync(code);
}
[WorkItem(543140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543140")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TypeOfExpression()
{
var code = @"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine({|r:typeof({|b:Dictionary<,>|})|}.IsGenericTypeDefinition);
}
}";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember1()
{
var code = @"using System;
class C { void M() { {|r:var x = new { {|b:String|} = true }; |}} }
";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember2()
{
var code = @"using System;
class C { void M() {
var String = 1;
{|r:var x = new { {|b:String|} };|}
} }
";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember3()
{
var code = @"using System;
class C { void M() { var x = new { String = {|b:true|} }; } }
";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember4()
{
var code = @"class Program
{
static void Main(string[] args)
{
var contacts = {|r:new[]
{
new {
Name = ""ddd"",
PhoneNumbers = new[] { ""206"", ""425"" }
},
new {
{|b:Name|} = ""sss"",
PhoneNumbers = new[] { ""206"" }
}
}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, WorkItem(543984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543984")]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AddressOfExpr1()
{
var code = @"
class C
{
unsafe void M()
{
int i = 5;
int* j = {|r:&{|b:i|}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, WorkItem(543984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543984")]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AddressOfExpr2()
{
var code = @"
class C
{
unsafe void M()
{
int i = 5;
int* j = {|b:&i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, WorkItem(544627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544627")]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task BaseKeyword()
{
var code = @"class C
{
void Goo()
{
{|r:{|b:base|}.ToString();|}
}
}
";
await TestSelectionAsync(code);
}
[WorkItem(545057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545057")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task RefvalueKeyword()
{
var code = @"using System;
class A
{
static void Goo(__arglist)
{
var argIterator = new ArgIterator(__arglist);
var typedReference = argIterator.GetNextArg();
Console.WriteLine(__reftype(typedReference));
Console.WriteLine({|r:__refvalue(typedReference, {|b:Int32|})|});
}
}";
await TestSelectionAsync(code);
}
[WorkItem(531286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531286")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NoCrashOnThrowWithoutCatchClause()
{
var code = @"public class Test
{
delegate int D();
static void Main()
{
try
{ }
catch
{ }
finally
{
{|b:((D)delegate { throw; return 0; })();|}
}
return 1;
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SimpleConditionalAccessExpressionSelectFirstExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:{|b:a|}?.Length |}?? 0;
}
}
class A
{
public int Length { get; internal set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SimpleConditionalAccessExpressionSelectSecondExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.{|b:Length|}|} ?? 0;
}
}
class A
{
public int Length { get; internal set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NestedConditionalAccessExpressionWithMemberBindingExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.{|b:Prop|}?.Length |}?? 0;
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int Length { get; set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NestedConditionalAccessExpressionWithMemberBindingExpressionSelectSecondExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.Prop?.{|b:Length|}|} ?? 0;
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int Length { get; set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NestedConditionalAccessExpressionWithInvocationExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.{|b:Method()|}?.Length |}?? 0;
}
}
class A
{
public B Method()
{
return new B();
}
}
class B
{
public int Length { get; set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(1228916, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1228916")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task DontCrashPastEndOfLine()
{
// 11 1
// 012345678901 2
var code = "class C { }\r\n";
// Markup parsing doesn't produce the right spans here, so supply one ourselves.
// Can be removed when https://github.com/dotnet/roslyn-sdk/issues/637 is fixed
// This span covers just the "\n"
var span = new TextSpan(12, 1);
await TestSelectionAsync(code, expectedFail: true, textSpanOverride: span);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod
{
public class SelectionValidatorTests : ExtractMethodBase
{
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest1()
{
var code = "{|b:using System;|}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest2()
{
var code = @"{|b:namespace A|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest3()
{
var code = @"namespace {|b:A|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest4()
{
var code = @"{|b:class|} A
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest5()
{
var code = @"class {|b:A|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest6()
{
var code = @"class A : {|b:object|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest7()
{
var code = @"class A : object, {|b:IDisposable|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest8()
{
var code = @"class A<{|b:T|}>
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest9()
{
var code = @"class A<T> where {|b:T|} : class
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest10()
{
var code = @"class A<T> where T : {|b:IDisposable|}
{
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest11()
{
var code = @"class A
{
{|b:A|} Method()
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest12()
{
var code = @"class A
{
A Method({|b:A|} a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest13()
{
var code = @"class A
{
A Method(A {|b:a|})
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest14()
{
var code = @"class A
{
[{|b:Goo|}]
A Method(A a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest15()
{
var code = @"class A
{
[Goo({|b:A|}=1)]
A Method(A a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest16()
{
var code = @"class A
{
[Goo(A={|b:1|})]
A Method(A a)
{
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest17()
{
var code = @"class A
{
const int {|b:i|} = 1;
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest18()
{
var code = @"class A
{
const {|b:int|} i = 1;
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest19()
{
var code = @"class A
{
const int i = {|b:1|};
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest20()
{
var code = @"class A
{
const int i = {|r:{|b:1 + |}2|};
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest21()
{
var code = @"class A
{
const int {|b:i = 1 + |}2;
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest22()
{
var code = @"class A
{
void Method1()
{
{|b:int i = 1;
}
void Method2()
{
int b = 2;|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest23()
{
var code = @"class A
{
void Method1()
{
{|b:int i = 1;
}|}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest24()
{
var code = @"class A
{
void Method1()
{
#region A
{|b:int i = 1;|}
#endRegion
}
}";
await TestSelectionAsync(code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest25()
{
var code = @"class A
{
void Method1()
{
{|b:#region A
int i = 1;|}
#endRegion
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest26()
{
var code = @"class A
{
void Method1()
{
#region A
{|b:int i = 1;
#endregion|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest27()
{
var code = @"class A
{
void Method1()
{
#region A
{|b:#endregion
int i = 1;|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest28()
{
var code = @"class A
{
void Method1()
{
#if true
{|b:int i = 1;
#endif|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest29()
{
var code = @"class A
{
void Method1()
{
{|b:#if true
int i = 1;|}
#endif
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest30()
{
var code = @"class A
{
void Method1()
{
#if true
{|b:#endif
int i = 1;|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest31()
{
var code = @"class A
{
void Method1()
{
#if false
{|b:#else
int i = 1;|}
#endif
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest32()
{
var code = @"class A
{
void Method1()
{
#if false
{|b:#elsif true
int i = 1;|}
#endif
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest33()
{
var code = @"class A
{
void Method1()
{
{|b:#if true
int i = 1;
#endif|}
}
}";
await TestSelectionAsync(code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest34()
{
var code = @"class A
{
void Method1()
{
{|b:#region
int i = 1;
#endregion|}
}
}";
await TestSelectionAsync(code);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest35()
{
var code = @"class A
{
void Method1()
{
{|b:// test|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest36()
{
var code = @"class A
{
IEnumerable<int> Method1()
{
{|r:{|b:yield return 1;|}|}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest37()
{
var code = @"class A
{
void Method1()
{
try
{
}
catch
{
{|b:throw;|}
}
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest38()
{
var code = @"class A
{
void Method1()
{
try
{
}
catch
{
{|b:throw new Exception();|}
}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest39()
{
var code = @"class A
{
void Method1()
{
{|r:{|b:System|}.Console.WriteLine(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest40()
{
var code = @"class A
{
void Method1()
{
{|r:{|b:System.Console|}.WriteLine(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest41()
{
var code = @"class A
{
void Method1()
{
{|r:{|b:System.Console.WriteLine|}(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest42()
{
var code = @"class A
{
void Method1()
{
{|r: System.{|b:Console|}.WriteLine(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest43()
{
var code = @"class A
{
void Method1()
{
{|r: System.{|b:Console.WriteLine|}(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540082")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest44()
{
var code = @"class A
{
void Method1()
{
{|r: System.Console.{|b:WriteLine|}(1);|}
}
}";
await TestSelectionAsync(code);
}
[WorkItem(539242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539242")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest45()
{
var code = @"class A
{
void Method1()
{
short[,] arr = {|r:new short[,] { {|b:{ 19, 19, 19 }|}, { 19, 19, 19 } }|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(539242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539242")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest46()
{
var code = @"class A
{
void Method1()
{
short[,] arr = {|r:{ {|b:{ 19, 19, 19 }|}, { 19, 19, 19 } }|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540338, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540338")]
[Fact]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectionTest47()
{
var code = @"using System;
class C
{
void M()
{
Action<string> d = s => Console.Write(s);
{|b:d +=|}
}
}
";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectIfWithReturn()
{
var code = @"class A
{
public void Method1()
{
bool b = true;
{|b:if (b)
return;|}
return;
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectConstIfWithReturn()
{
var code = @"class A
{
public void Method1()
{
const bool b = true;
{|b:if (b)
return;|}
Console.WriteLine();
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectReturnButNotAllCodePathsContainAReturn()
{
var code = @"class A
{
public void Method1(bool b1, bool b2)
{
if (b1)
{
{|b:if (b2)
return;
Console.WriteLine();|}
}
Console.WriteLine();
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectIfBranchWhereNotAllPathsReturn()
{
var code = @"class A
{
int Method8(int i)
{
{|b:if (i > 100)
{
return i++;
}
else if (i > 90)
{
return i--;
}
else
{
i++;
}|}
return i;
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCatchFilterClause()
{
var code = @"class A
{
int method()
{
try
{
Console.Write(5);
}
catch (Exception ex) if ({|b:ex.Message == ""goo""|})
{
throw;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCatchFilterClause2()
{
var code = @"class A
{
int method()
{
int i = 5;
try
{
Console.Write(5);
}
catch (Exception ex) if ({|b:i == 5|})
{
Console.Write(5);
i = 0;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectWithinCatchFilterClause()
{
var code = @"class A
{
int method()
{
try
{
Console.Write(5);
}
catch (Exception ex) if ({|b:ex.Message|} == ""goo"")
{
throw;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectWithinCatchFilterClause2()
{
var code = @"class A
{
int method()
{
try
{
Console.Write(5);
}
catch (Exception ex) if (ex.Message == {|b:""goo""|})
{
throw;
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLValueOfPlusEqualsOperator()
{
var code = @"class A
{
int method()
{
int i = 0;
{|r:{|b:i|} += 1;|}
return i;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectRValueOfPlusEqualsOperator()
{
var code = @"class A
{
int method()
{
int i = 0;
i += {|b:1|};
return i;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectRValueOfPredecrementOperator()
{
var code = @"class A
{
string method(string s, int i)
{
string[] myvar = new string[i];
myvar[0] = s;
myvar[{|r:--{|b:i|}|}] = s + i.ToString();
return myvar[i];
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectArrayWithDecrementIndex()
{
var code = @"class A
{
string method(string s, int i)
{
string[] myvar = new string[i];
myvar[0] = s;
{|r:{|b:myvar[--i]|} = s + i.ToString();|}
return myvar[i];
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCastOperator()
{
var code = @"class A
{
int method(string goo)
{
String bar = {|b:(String)goo|};
return bar.Length;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLHSOfPostIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:i|}++|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectPostIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:i{|b:++|}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectRHSOfPreIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:++|}i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectPreIncrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:++|}i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectPreDecrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:--|}i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLHSOfPostDecrementOperator()
{
var code = @"class A
{
int method(int i)
{
return {|r:{|b:i|}--|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectUnaryPlusOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:+|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectUnaryMinusOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:-|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLogicalNegationOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:!|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectBitwiseNegationOperator()
{
var code = @"class A
{
int method(int i)
{
int j = {|r:{|b:~|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectCastOperator2()
{
var code = @"class A
{
int method(double i)
{
int j = {|r:{|b:(int)|}i|};
return j;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectInvalidSubexpressionToExpand()
{
var code = @"class A
{
public int method(int a, int b, int c)
{
return {|r:a + {|b:b + c|}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectValidSubexpressionAndHenceDontExpand()
{
var code = @"class A
{
public int method(int a, int b, int c)
{
return {|b:a + b|} + c;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectLHSOfMinusEqualsOperator()
{
var code = @"class A
{
public int method(int a, int b)
{
{|r:{|b:a|} -= b;|}
return a;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectInnerBlockPartially()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
ArrayList ar = null;
foreach (object var in ar)
{
{|r:{|b:System.Console.WriteLine();
foreach (object var2 in ar)
{
System.Console.WriteLine();|}
}|}
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectInnerBlockWithoutBracesPartially()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
while (true)
{
int i = 0;
{|r: if (i == 0)
Console.WriteLine(){|b:;
Console.WriteLine();|}|}
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectBeginningBrace()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
if (true) {|r:{|b:{|} }|}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectAcrossBlocks1()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
if (true)
{
{|r: for (int i = 0; i < 100; i++)
{
{|b:System.Console.WriteLine();
}
System.Console.WriteLine();|}|}
}
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectMethodParameters()
{
var code = @"using System;
using System.Collections;
class A
{
void method()
{
double x1 = 10;
double y1 = 20;
double z1 = 30;
double ret = {|r:sum({|b:ref x1, y1, z1|})|};
}
double sum(ref double x, double y, double z)
{
x++;
return x + y + z;
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectChainedInvocations1()
{
var code = @"using System;
using System.Collections;
class Test
{
class B
{
public int c()
{
return 100;
}
}
class A
{
public B b = new B();
}
void method()
{
A a = new A();
{|b:a.b|}.c();
}
}";
await TestSelectionAsync(code);
}
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SelectChainedInvocations2()
{
var code = @"using System;
using System.Collections;
class Test
{
class B
{
public int c()
{
return 100;
}
}
class A
{
public B b = new B();
}
void method()
{
A a = new A();
{|r: a.{|b:b.c()|}|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540474")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task GotoStatement()
{
var code = @"using System;
using System.Reflection.Emit;
class Program
{
public delegate R Del<in T, out R>(T arg);
static void Main(string[] args)
{
Del<ArgumentException, Exception> del = {|r:(arg) =>
{
goto {|b:Label|};
Label:
return new ArgumentException();
}|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540481")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task BugFix6750()
{
var code = @"using System;
class Program
{
int[] array = new int[{|b:1|}];
}";
await TestSelectionAsync(code);
}
[WorkItem(540481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540481")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task BugFix6750_1()
{
var code = @"using System;
class Program
{
int[] array = {|r:new int[{|b:1|}] { 1 }|};
}";
await TestSelectionAsync(code);
}
[WorkItem(542201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542201")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task MalformedCode_NoOuterType()
{
var code = @"x(a){
{|b:for ();|}
}
";
await TestSelectionAsync(code, expectedFail: true);
}
[WorkItem(542210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542210")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NoQueryContinuation()
{
var code = @"using System.Linq;
class P
{
static void Main()
{
var src = new int[] { 4, 5 };
var q = {|r:from x in src
select x into y
{|b:select y|}|};
}
}";
await TestSelectionAsync(code);
}
[WorkItem(540787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540787")]
[WorkItem(542722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542722")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task DontCrash()
=> await IterateAllAsync(TestResource.AllInOneCSharpCode);
[WorkItem(9931, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task ExtractMethodIdentifierAtEndOfInteractiveBuffer()
{
var code = @"using System.Console;
WriteLine();
{|r:{|b:Diagnostic|}|}";
await TestSelectionAsync(code, expectedFail: true);
}
[WorkItem(543020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543020")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task MemberAccessStructAsExpression()
{
var code = @"struct S
{
public float X;
public float Y;
public float Z;
void M()
{
if (3 < 3.4)
{
S s;
if (s.X < 3)
{
s = GetS();
{|r:{|b:s|}.Z = 10f;|}
}
else
{
}
}
else
{
}
}
private static S GetS()
{
return new S();
}
} ";
await TestSelectionAsync(code);
}
[WorkItem(543140, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543140")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task TypeOfExpression()
{
var code = @"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine({|r:typeof({|b:Dictionary<,>|})|}.IsGenericTypeDefinition);
}
}";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember1()
{
var code = @"using System;
class C { void M() { {|r:var x = new { {|b:String|} = true }; |}} }
";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember2()
{
var code = @"using System;
class C { void M() {
var String = 1;
{|r:var x = new { {|b:String|} };|}
} }
";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember3()
{
var code = @"using System;
class C { void M() { var x = new { String = {|b:true|} }; } }
";
await TestSelectionAsync(code);
}
[WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AnonymousTypeMember4()
{
var code = @"class Program
{
static void Main(string[] args)
{
var contacts = {|r:new[]
{
new {
Name = ""ddd"",
PhoneNumbers = new[] { ""206"", ""425"" }
},
new {
{|b:Name|} = ""sss"",
PhoneNumbers = new[] { ""206"" }
}
}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, WorkItem(543984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543984")]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AddressOfExpr1()
{
var code = @"
class C
{
unsafe void M()
{
int i = 5;
int* j = {|r:&{|b:i|}|};
}
}";
await TestSelectionAsync(code);
}
[Fact, WorkItem(543984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543984")]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task AddressOfExpr2()
{
var code = @"
class C
{
unsafe void M()
{
int i = 5;
int* j = {|b:&i|};
}
}";
await TestSelectionAsync(code);
}
[Fact, WorkItem(544627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544627")]
[Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task BaseKeyword()
{
var code = @"class C
{
void Goo()
{
{|r:{|b:base|}.ToString();|}
}
}
";
await TestSelectionAsync(code);
}
[WorkItem(545057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545057")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task RefvalueKeyword()
{
var code = @"using System;
class A
{
static void Goo(__arglist)
{
var argIterator = new ArgIterator(__arglist);
var typedReference = argIterator.GetNextArg();
Console.WriteLine(__reftype(typedReference));
Console.WriteLine({|r:__refvalue(typedReference, {|b:Int32|})|});
}
}";
await TestSelectionAsync(code);
}
[WorkItem(531286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531286")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NoCrashOnThrowWithoutCatchClause()
{
var code = @"public class Test
{
delegate int D();
static void Main()
{
try
{ }
catch
{ }
finally
{
{|b:((D)delegate { throw; return 0; })();|}
}
return 1;
}
}";
await TestSelectionAsync(code, expectedFail: true);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SimpleConditionalAccessExpressionSelectFirstExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:{|b:a|}?.Length |}?? 0;
}
}
class A
{
public int Length { get; internal set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task SimpleConditionalAccessExpressionSelectSecondExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.{|b:Length|}|} ?? 0;
}
}
class A
{
public int Length { get; internal set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NestedConditionalAccessExpressionWithMemberBindingExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.{|b:Prop|}?.Length |}?? 0;
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int Length { get; set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NestedConditionalAccessExpressionWithMemberBindingExpressionSelectSecondExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.Prop?.{|b:Length|}|} ?? 0;
}
}
class A
{
public B Prop { get; set; }
}
class B
{
public int Length { get; set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(751, "https://github.com/dotnet/roslyn/issues/751")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task NestedConditionalAccessExpressionWithInvocationExpression()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
A a = new A();
var l = {|r:a?.{|b:Method()|}?.Length |}?? 0;
}
}
class A
{
public B Method()
{
return new B();
}
}
class B
{
public int Length { get; set; }
}";
await TestSelectionAsync(code);
}
[WorkItem(1228916, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1228916")]
[Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)]
public async Task DontCrashPastEndOfLine()
{
// 11 1
// 012345678901 2
var code = "class C { }\r\n";
// Markup parsing doesn't produce the right spans here, so supply one ourselves.
// Can be removed when https://github.com/dotnet/roslyn-sdk/issues/637 is fixed
// This span covers just the "\n"
var span = new TextSpan(12, 1);
await TestSelectionAsync(code, expectedFail: true, textSpanOverride: span);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/GoToDefinition/AbstractFindDefinitionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.GoToDefinition
{
internal class AbstractFindDefinitionService : IFindDefinitionService
{
public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(
Document document, int position, CancellationToken cancellationToken)
{
var symbolService = document.GetRequiredLanguageService<IGoToDefinitionSymbolService>();
var (symbol, _) = await symbolService.GetSymbolAndBoundSpanAsync(document, position, includeType: true, cancellationToken).ConfigureAwait(false);
// Try to compute source definitions from symbol.
return symbol != null
? NavigableItemFactory.GetItemsFromPreferredSourceLocations(document.Project.Solution, symbol, displayTaggedParts: null, cancellationToken: cancellationToken)
: ImmutableArray<INavigableItem>.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.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.GoToDefinition
{
internal class AbstractFindDefinitionService : IFindDefinitionService
{
public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(
Document document, int position, CancellationToken cancellationToken)
{
var symbolService = document.GetRequiredLanguageService<IGoToDefinitionSymbolService>();
var (symbol, _) = await symbolService.GetSymbolAndBoundSpanAsync(document, position, includeType: true, cancellationToken).ConfigureAwait(false);
// Try to compute source definitions from symbol.
return symbol != null
? NavigableItemFactory.GetItemsFromPreferredSourceLocations(document.Project.Solution, symbol, displayTaggedParts: null, cancellationToken: cancellationToken)
: ImmutableArray<INavigableItem>.Empty;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationNameCompletionProvider.DeclarationInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class DeclarationNameCompletionProvider
{
internal struct NameDeclarationInfo
{
private static readonly ImmutableArray<SymbolKindOrTypeKind> s_parameterSyntaxKind =
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Parameter));
private static readonly ImmutableArray<SymbolKindOrTypeKind> s_propertySyntaxKind =
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Property));
public NameDeclarationInfo(
ImmutableArray<SymbolKindOrTypeKind> possibleSymbolKinds,
Accessibility? accessibility,
DeclarationModifiers declarationModifiers,
ITypeSymbol type,
IAliasSymbol alias)
{
PossibleSymbolKinds = possibleSymbolKinds;
DeclaredAccessibility = accessibility;
Modifiers = declarationModifiers;
Type = type;
Alias = alias;
}
public ImmutableArray<SymbolKindOrTypeKind> PossibleSymbolKinds { get; }
public DeclarationModifiers Modifiers { get; }
public ITypeSymbol Type { get; }
public IAliasSymbol Alias { get; }
public Accessibility? DeclaredAccessibility { get; }
internal static async Task<NameDeclarationInfo> GetDeclarationInfoAsync(Document document, int position, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken).GetPreviousTokenIfTouchingWord(position);
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.SpanStart, cancellationToken).ConfigureAwait(false);
var typeInferenceService = document.GetLanguageService<ITypeInferenceService>();
if (IsTupleTypeElement(token, semanticModel, cancellationToken, out var result)
|| IsPrimaryConstructorParameter(token, semanticModel, cancellationToken, out result)
|| IsParameterDeclaration(token, semanticModel, cancellationToken, out result)
|| IsTypeParameterDeclaration(token, out result)
|| IsLocalFunctionDeclaration(token, semanticModel, cancellationToken, out result)
|| IsLocalVariableDeclaration(token, semanticModel, cancellationToken, out result)
|| IsEmbeddedVariableDeclaration(token, semanticModel, cancellationToken, out result)
|| IsForEachVariableDeclaration(token, semanticModel, cancellationToken, out result)
|| IsIncompleteMemberDeclaration(token, semanticModel, cancellationToken, out result)
|| IsFieldDeclaration(token, semanticModel, cancellationToken, out result)
|| IsMethodDeclaration(token, semanticModel, cancellationToken, out result)
|| IsPropertyDeclaration(token, semanticModel, cancellationToken, out result)
|| IsPossibleOutVariableDeclaration(token, semanticModel, typeInferenceService, cancellationToken, out result)
|| IsTupleLiteralElement(token, semanticModel, cancellationToken, out result)
|| IsPossibleVariableOrLocalMethodDeclaration(token, semanticModel, cancellationToken, out result)
|| IsPatternMatching(token, semanticModel, cancellationToken, out result))
{
return result;
}
return default;
}
private static bool IsTupleTypeElement(
SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsFollowingTypeOrComma<TupleElementSyntax>(
token,
semanticModel,
tupleElement => tupleElement.Type,
_ => default(SyntaxTokenList),
_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken);
return result.Type != null;
}
private static bool IsTupleLiteralElement(
SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
// Incomplete code like
// void Do()
// {
// (System.Array array, System.Action $$
// gets parsed as a tuple expression. We can figure out the type in such cases.
// For a legit tuple expression we can't provide any completion.
if (token.GetAncestor(node => node.IsKind(SyntaxKind.TupleExpression)) != null)
{
result = IsFollowingTypeOrComma<ArgumentSyntax>(
token,
semanticModel,
GetNodeDenotingTheTypeOfTupleArgument,
_ => default(SyntaxTokenList),
_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken);
return result.Type != null;
}
result = default;
return false;
}
private static bool IsPossibleOutVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
ITypeInferenceService typeInferenceService, CancellationToken cancellationToken, out NameDeclarationInfo result)
{
if (!token.IsKind(SyntaxKind.IdentifierToken) || !token.Parent.IsKind(SyntaxKind.IdentifierName))
{
result = default;
return false;
}
var argument = token.Parent.Parent as ArgumentSyntax // var is child of ArgumentSyntax, eg. Goo(out var $$
?? token.Parent.Parent.Parent as ArgumentSyntax; // var is child of DeclarationExpression
// under ArgumentSyntax, eg. Goo(out var a$$
if (argument == null || !argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword))
{
result = default;
return false;
}
var type = typeInferenceService.InferType(semanticModel, argument.SpanStart, objectAsDefault: false, cancellationToken: cancellationToken);
if (type != null)
{
result = new NameDeclarationInfo(
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)),
Accessibility.NotApplicable,
new DeclarationModifiers(),
type,
alias: null);
return true;
}
result = default;
return false;
}
private static bool IsPossibleVariableOrLocalMethodDeclaration(
SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<ExpressionStatementSyntax>(
token, semanticModel,
e => e.Expression,
_ => default,
_ => ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(MethodKind.LocalFunction)),
cancellationToken);
return result.Type != null;
}
private static bool IsPropertyDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<PropertyDeclarationSyntax>(
token,
semanticModel,
m => m.Type,
m => m.Modifiers,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsMethodDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<MethodDeclarationSyntax>(
token,
semanticModel,
m => m.ReturnType,
m => m.Modifiers,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static NameDeclarationInfo IsFollowingTypeOrComma<TSyntaxNode>(SyntaxToken token,
SemanticModel semanticModel,
Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter,
Func<TSyntaxNode, SyntaxTokenList?> modifierGetter,
Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
if (!IsPossibleTypeToken(token) && !token.IsKind(SyntaxKind.CommaToken))
{
return default;
}
var target = token.GetAncestor<TSyntaxNode>();
if (target == null)
{
return default;
}
if (token.IsKind(SyntaxKind.CommaToken) && token.Parent != target)
{
return default;
}
var typeSyntax = typeSyntaxGetter(target);
if (typeSyntax == null)
{
return default;
}
if (!token.IsKind(SyntaxKind.CommaToken) && token != typeSyntax.GetLastToken())
{
return default;
}
var modifiers = modifierGetter(target);
if (modifiers == null)
{
return default;
}
var alias = semanticModel.GetAliasInfo(typeSyntax, cancellationToken);
var type = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
return new NameDeclarationInfo(
possibleDeclarationComputer(GetDeclarationModifiers(modifiers.Value)),
GetAccessibility(modifiers.Value),
GetDeclarationModifiers(modifiers.Value),
type,
alias);
}
private static NameDeclarationInfo IsLastTokenOfType<TSyntaxNode>(
SyntaxToken token,
SemanticModel semanticModel,
Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter,
Func<TSyntaxNode, SyntaxTokenList> modifierGetter,
Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
if (!IsPossibleTypeToken(token))
{
return default;
}
var target = token.GetAncestor<TSyntaxNode>();
if (target == null)
{
return default;
}
var typeSyntax = typeSyntaxGetter(target);
if (typeSyntax == null || token != typeSyntax.GetLastToken())
{
return default;
}
var modifiers = modifierGetter(target);
return new NameDeclarationInfo(
possibleDeclarationComputer(GetDeclarationModifiers(modifiers)),
GetAccessibility(modifiers),
GetDeclarationModifiers(modifiers),
semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type,
semanticModel.GetAliasInfo(typeSyntax, cancellationToken));
}
private static bool IsFieldDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel,
v => v.Type,
v => v.Parent is FieldDeclarationSyntax f ? f.Modifiers : (SyntaxTokenList?)null,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsIncompleteMemberDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<IncompleteMemberSyntax>(token, semanticModel,
i => i.Type,
i => i.Modifiers,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsLocalFunctionDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<LocalFunctionStatementSyntax>(token, semanticModel,
typeSyntaxGetter: f => f.ReturnType,
modifierGetter: f => f.Modifiers,
possibleDeclarationComputer: GetPossibleLocalDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsLocalVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
// If we only have a type, this can still end up being a local function (depending on the modifiers).
var possibleDeclarationComputer = token.IsKind(SyntaxKind.CommaToken)
? (Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>>)
(_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)))
: GetPossibleLocalDeclarations;
result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel,
typeSyntaxGetter: v => v.Type,
modifierGetter: v => v.Parent is LocalDeclarationStatementSyntax localDeclaration
? localDeclaration.Modifiers
: (SyntaxTokenList?)null, // Return null to bail out.
possibleDeclarationComputer,
cancellationToken);
if (result.Type != null)
{
return true;
}
// If the type has a trailing question mark, we may parse it as a conditional access expression.
// We will use the condition as the type to bind; we won't make the type we bind nullable
// because we ignore nullability when generating names anyways
if (token.IsKind(SyntaxKind.QuestionToken) &&
token.Parent is ConditionalExpressionSyntax conditionalExpressionSyntax)
{
var symbolInfo = semanticModel.GetSymbolInfo(conditionalExpressionSyntax.Condition);
if (symbolInfo.GetAnySymbol() is ITypeSymbol type)
{
var alias = semanticModel.GetAliasInfo(conditionalExpressionSyntax.Condition, cancellationToken);
result = new NameDeclarationInfo(
possibleDeclarationComputer(default),
accessibility: null,
declarationModifiers: default,
type,
alias);
return true;
}
}
return false;
}
private static bool IsEmbeddedVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel,
typeSyntaxGetter: v => v.Type,
modifierGetter: v => v.Parent is UsingStatementSyntax || v.Parent is ForStatementSyntax
? default(SyntaxTokenList)
: (SyntaxTokenList?)null, // Return null to bail out.
possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)),
cancellationToken);
return result.Type != null;
}
private static bool IsForEachVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
// This is parsed as ForEachVariableStatementSyntax:
// foreach (int $$
result = IsLastTokenOfType<CommonForEachStatementSyntax>(token, semanticModel,
typeSyntaxGetter: f =>
f is ForEachStatementSyntax forEachStatement ? forEachStatement.Type :
f is ForEachVariableStatementSyntax forEachVariableStatement ? forEachVariableStatement.Variable :
null, // Return null to bail out.
modifierGetter: f => default,
possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)),
cancellationToken);
return result.Type != null;
}
private static bool IsTypeParameterDeclaration(SyntaxToken token, out NameDeclarationInfo result)
{
if (token.IsKind(SyntaxKind.LessThanToken, SyntaxKind.CommaToken) &&
token.Parent.IsKind(SyntaxKind.TypeParameterList))
{
result = new NameDeclarationInfo(
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.TypeParameter)),
Accessibility.NotApplicable,
new DeclarationModifiers(),
type: null,
alias: null);
return true;
}
result = default;
return false;
}
private static bool IsPrimaryConstructorParameter(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<ParameterSyntax>(
token, semanticModel,
p => p.Type,
_ => default,
_ => s_propertySyntaxKind,
cancellationToken);
if (result.Type != null &&
token.GetAncestor<ParameterSyntax>().Parent.IsParentKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration))
{
return true;
}
result = default;
return false;
}
private static bool IsParameterDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<ParameterSyntax>(
token, semanticModel,
p => p.Type,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
return result.Type != null;
}
private static bool IsPatternMatching(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = default;
if (token.Parent.IsParentKind(SyntaxKind.IsExpression))
{
result = IsLastTokenOfType<BinaryExpressionSyntax>(
token, semanticModel,
b => b.Right,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
}
else if (token.Parent.IsParentKind(SyntaxKind.CaseSwitchLabel))
{
result = IsLastTokenOfType<CaseSwitchLabelSyntax>(
token, semanticModel,
b => b.Value,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
}
else if (token.Parent.IsParentKind(SyntaxKind.DeclarationPattern))
{
result = IsLastTokenOfType<DeclarationPatternSyntax>(
token, semanticModel,
b => b.Type,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
}
return result.Type != null;
}
private static bool IsPossibleTypeToken(SyntaxToken token) =>
token.IsKind(
SyntaxKind.IdentifierToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.CloseBracketToken,
SyntaxKind.QuestionToken)
|| token.Parent.IsKind(SyntaxKind.PredefinedType);
private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleMemberDeclarations(DeclarationModifiers modifiers)
{
if (modifiers.IsConst || modifiers.IsReadOnly)
{
return ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field));
}
var possibleTypes = ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary));
if (modifiers.IsAbstract || modifiers.IsVirtual || modifiers.IsSealed || modifiers.IsOverride)
{
possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field));
}
if (modifiers.IsAsync || modifiers.IsPartial)
{
// Fields and properties cannot be async or partial.
possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field));
possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Property));
}
return possibleTypes;
}
private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleLocalDeclarations(DeclarationModifiers modifiers)
{
return
modifiers.IsConst
? ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)) :
modifiers.IsAsync || modifiers.IsUnsafe
? ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.LocalFunction)) :
ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(MethodKind.LocalFunction));
}
private static DeclarationModifiers GetDeclarationModifiers(SyntaxTokenList modifiers)
{
var declarationModifiers = new DeclarationModifiers();
foreach (var modifer in modifiers)
{
switch (modifer.Kind())
{
case SyntaxKind.StaticKeyword:
declarationModifiers = declarationModifiers.WithIsStatic(true);
continue;
case SyntaxKind.AbstractKeyword:
declarationModifiers = declarationModifiers.WithIsAbstract(true);
continue;
case SyntaxKind.NewKeyword:
declarationModifiers = declarationModifiers.WithIsNew(true);
continue;
case SyntaxKind.UnsafeKeyword:
declarationModifiers = declarationModifiers.WithIsUnsafe(true);
continue;
case SyntaxKind.ReadOnlyKeyword:
declarationModifiers = declarationModifiers.WithIsReadOnly(true);
continue;
case SyntaxKind.VirtualKeyword:
declarationModifiers = declarationModifiers.WithIsVirtual(true);
continue;
case SyntaxKind.OverrideKeyword:
declarationModifiers = declarationModifiers.WithIsOverride(true);
continue;
case SyntaxKind.SealedKeyword:
declarationModifiers = declarationModifiers.WithIsSealed(true);
continue;
case SyntaxKind.ConstKeyword:
declarationModifiers = declarationModifiers.WithIsConst(true);
continue;
case SyntaxKind.AsyncKeyword:
declarationModifiers = declarationModifiers.WithAsync(true);
continue;
case SyntaxKind.PartialKeyword:
declarationModifiers = declarationModifiers.WithPartial(true);
continue;
}
}
return declarationModifiers;
}
private static Accessibility? GetAccessibility(SyntaxTokenList modifiers)
{
for (var i = modifiers.Count - 1; i >= 0; i--)
{
var modifier = modifiers[i];
switch (modifier.Kind())
{
case SyntaxKind.PrivateKeyword:
return Accessibility.Private;
case SyntaxKind.PublicKeyword:
return Accessibility.Public;
case SyntaxKind.ProtectedKeyword:
return Accessibility.Protected;
case SyntaxKind.InternalKeyword:
return Accessibility.Internal;
}
}
return null;
}
private static SyntaxNode GetNodeDenotingTheTypeOfTupleArgument(ArgumentSyntax argumentSyntax)
{
switch (argumentSyntax.Expression?.Kind())
{
case SyntaxKind.DeclarationExpression:
// The parser found a declaration as in (System.Action action, System.Array a$$)
// we need the type part of the declaration expression.
return ((DeclarationExpressionSyntax)argumentSyntax.Expression).Type;
default:
// We assume the parser found something that represents something named,
// e.g. a MemberAccessExpression as in (System.Action action, System.Array $$)
// We also assume that this name could be resolved to a type.
return argumentSyntax.Expression;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class DeclarationNameCompletionProvider
{
internal struct NameDeclarationInfo
{
private static readonly ImmutableArray<SymbolKindOrTypeKind> s_parameterSyntaxKind =
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Parameter));
private static readonly ImmutableArray<SymbolKindOrTypeKind> s_propertySyntaxKind =
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Property));
public NameDeclarationInfo(
ImmutableArray<SymbolKindOrTypeKind> possibleSymbolKinds,
Accessibility? accessibility,
DeclarationModifiers declarationModifiers,
ITypeSymbol type,
IAliasSymbol alias)
{
PossibleSymbolKinds = possibleSymbolKinds;
DeclaredAccessibility = accessibility;
Modifiers = declarationModifiers;
Type = type;
Alias = alias;
}
public ImmutableArray<SymbolKindOrTypeKind> PossibleSymbolKinds { get; }
public DeclarationModifiers Modifiers { get; }
public ITypeSymbol Type { get; }
public IAliasSymbol Alias { get; }
public Accessibility? DeclaredAccessibility { get; }
internal static async Task<NameDeclarationInfo> GetDeclarationInfoAsync(Document document, int position, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken).GetPreviousTokenIfTouchingWord(position);
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.SpanStart, cancellationToken).ConfigureAwait(false);
var typeInferenceService = document.GetLanguageService<ITypeInferenceService>();
if (IsTupleTypeElement(token, semanticModel, cancellationToken, out var result)
|| IsPrimaryConstructorParameter(token, semanticModel, cancellationToken, out result)
|| IsParameterDeclaration(token, semanticModel, cancellationToken, out result)
|| IsTypeParameterDeclaration(token, out result)
|| IsLocalFunctionDeclaration(token, semanticModel, cancellationToken, out result)
|| IsLocalVariableDeclaration(token, semanticModel, cancellationToken, out result)
|| IsEmbeddedVariableDeclaration(token, semanticModel, cancellationToken, out result)
|| IsForEachVariableDeclaration(token, semanticModel, cancellationToken, out result)
|| IsIncompleteMemberDeclaration(token, semanticModel, cancellationToken, out result)
|| IsFieldDeclaration(token, semanticModel, cancellationToken, out result)
|| IsMethodDeclaration(token, semanticModel, cancellationToken, out result)
|| IsPropertyDeclaration(token, semanticModel, cancellationToken, out result)
|| IsPossibleOutVariableDeclaration(token, semanticModel, typeInferenceService, cancellationToken, out result)
|| IsTupleLiteralElement(token, semanticModel, cancellationToken, out result)
|| IsPossibleVariableOrLocalMethodDeclaration(token, semanticModel, cancellationToken, out result)
|| IsPatternMatching(token, semanticModel, cancellationToken, out result))
{
return result;
}
return default;
}
private static bool IsTupleTypeElement(
SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsFollowingTypeOrComma<TupleElementSyntax>(
token,
semanticModel,
tupleElement => tupleElement.Type,
_ => default(SyntaxTokenList),
_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken);
return result.Type != null;
}
private static bool IsTupleLiteralElement(
SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
// Incomplete code like
// void Do()
// {
// (System.Array array, System.Action $$
// gets parsed as a tuple expression. We can figure out the type in such cases.
// For a legit tuple expression we can't provide any completion.
if (token.GetAncestor(node => node.IsKind(SyntaxKind.TupleExpression)) != null)
{
result = IsFollowingTypeOrComma<ArgumentSyntax>(
token,
semanticModel,
GetNodeDenotingTheTypeOfTupleArgument,
_ => default(SyntaxTokenList),
_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken);
return result.Type != null;
}
result = default;
return false;
}
private static bool IsPossibleOutVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
ITypeInferenceService typeInferenceService, CancellationToken cancellationToken, out NameDeclarationInfo result)
{
if (!token.IsKind(SyntaxKind.IdentifierToken) || !token.Parent.IsKind(SyntaxKind.IdentifierName))
{
result = default;
return false;
}
var argument = token.Parent.Parent as ArgumentSyntax // var is child of ArgumentSyntax, eg. Goo(out var $$
?? token.Parent.Parent.Parent as ArgumentSyntax; // var is child of DeclarationExpression
// under ArgumentSyntax, eg. Goo(out var a$$
if (argument == null || !argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword))
{
result = default;
return false;
}
var type = typeInferenceService.InferType(semanticModel, argument.SpanStart, objectAsDefault: false, cancellationToken: cancellationToken);
if (type != null)
{
result = new NameDeclarationInfo(
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)),
Accessibility.NotApplicable,
new DeclarationModifiers(),
type,
alias: null);
return true;
}
result = default;
return false;
}
private static bool IsPossibleVariableOrLocalMethodDeclaration(
SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<ExpressionStatementSyntax>(
token, semanticModel,
e => e.Expression,
_ => default,
_ => ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(MethodKind.LocalFunction)),
cancellationToken);
return result.Type != null;
}
private static bool IsPropertyDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<PropertyDeclarationSyntax>(
token,
semanticModel,
m => m.Type,
m => m.Modifiers,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsMethodDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<MethodDeclarationSyntax>(
token,
semanticModel,
m => m.ReturnType,
m => m.Modifiers,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static NameDeclarationInfo IsFollowingTypeOrComma<TSyntaxNode>(SyntaxToken token,
SemanticModel semanticModel,
Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter,
Func<TSyntaxNode, SyntaxTokenList?> modifierGetter,
Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
if (!IsPossibleTypeToken(token) && !token.IsKind(SyntaxKind.CommaToken))
{
return default;
}
var target = token.GetAncestor<TSyntaxNode>();
if (target == null)
{
return default;
}
if (token.IsKind(SyntaxKind.CommaToken) && token.Parent != target)
{
return default;
}
var typeSyntax = typeSyntaxGetter(target);
if (typeSyntax == null)
{
return default;
}
if (!token.IsKind(SyntaxKind.CommaToken) && token != typeSyntax.GetLastToken())
{
return default;
}
var modifiers = modifierGetter(target);
if (modifiers == null)
{
return default;
}
var alias = semanticModel.GetAliasInfo(typeSyntax, cancellationToken);
var type = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
return new NameDeclarationInfo(
possibleDeclarationComputer(GetDeclarationModifiers(modifiers.Value)),
GetAccessibility(modifiers.Value),
GetDeclarationModifiers(modifiers.Value),
type,
alias);
}
private static NameDeclarationInfo IsLastTokenOfType<TSyntaxNode>(
SyntaxToken token,
SemanticModel semanticModel,
Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter,
Func<TSyntaxNode, SyntaxTokenList> modifierGetter,
Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer,
CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
{
if (!IsPossibleTypeToken(token))
{
return default;
}
var target = token.GetAncestor<TSyntaxNode>();
if (target == null)
{
return default;
}
var typeSyntax = typeSyntaxGetter(target);
if (typeSyntax == null || token != typeSyntax.GetLastToken())
{
return default;
}
var modifiers = modifierGetter(target);
return new NameDeclarationInfo(
possibleDeclarationComputer(GetDeclarationModifiers(modifiers)),
GetAccessibility(modifiers),
GetDeclarationModifiers(modifiers),
semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type,
semanticModel.GetAliasInfo(typeSyntax, cancellationToken));
}
private static bool IsFieldDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel,
v => v.Type,
v => v.Parent is FieldDeclarationSyntax f ? f.Modifiers : (SyntaxTokenList?)null,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsIncompleteMemberDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<IncompleteMemberSyntax>(token, semanticModel,
i => i.Type,
i => i.Modifiers,
GetPossibleMemberDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsLocalFunctionDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<LocalFunctionStatementSyntax>(token, semanticModel,
typeSyntaxGetter: f => f.ReturnType,
modifierGetter: f => f.Modifiers,
possibleDeclarationComputer: GetPossibleLocalDeclarations,
cancellationToken);
return result.Type != null;
}
private static bool IsLocalVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
// If we only have a type, this can still end up being a local function (depending on the modifiers).
var possibleDeclarationComputer = token.IsKind(SyntaxKind.CommaToken)
? (Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>>)
(_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)))
: GetPossibleLocalDeclarations;
result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel,
typeSyntaxGetter: v => v.Type,
modifierGetter: v => v.Parent is LocalDeclarationStatementSyntax localDeclaration
? localDeclaration.Modifiers
: (SyntaxTokenList?)null, // Return null to bail out.
possibleDeclarationComputer,
cancellationToken);
if (result.Type != null)
{
return true;
}
// If the type has a trailing question mark, we may parse it as a conditional access expression.
// We will use the condition as the type to bind; we won't make the type we bind nullable
// because we ignore nullability when generating names anyways
if (token.IsKind(SyntaxKind.QuestionToken) &&
token.Parent is ConditionalExpressionSyntax conditionalExpressionSyntax)
{
var symbolInfo = semanticModel.GetSymbolInfo(conditionalExpressionSyntax.Condition);
if (symbolInfo.GetAnySymbol() is ITypeSymbol type)
{
var alias = semanticModel.GetAliasInfo(conditionalExpressionSyntax.Condition, cancellationToken);
result = new NameDeclarationInfo(
possibleDeclarationComputer(default),
accessibility: null,
declarationModifiers: default,
type,
alias);
return true;
}
}
return false;
}
private static bool IsEmbeddedVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel,
typeSyntaxGetter: v => v.Type,
modifierGetter: v => v.Parent is UsingStatementSyntax || v.Parent is ForStatementSyntax
? default(SyntaxTokenList)
: (SyntaxTokenList?)null, // Return null to bail out.
possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)),
cancellationToken);
return result.Type != null;
}
private static bool IsForEachVariableDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
// This is parsed as ForEachVariableStatementSyntax:
// foreach (int $$
result = IsLastTokenOfType<CommonForEachStatementSyntax>(token, semanticModel,
typeSyntaxGetter: f =>
f is ForEachStatementSyntax forEachStatement ? forEachStatement.Type :
f is ForEachVariableStatementSyntax forEachVariableStatement ? forEachVariableStatement.Variable :
null, // Return null to bail out.
modifierGetter: f => default,
possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)),
cancellationToken);
return result.Type != null;
}
private static bool IsTypeParameterDeclaration(SyntaxToken token, out NameDeclarationInfo result)
{
if (token.IsKind(SyntaxKind.LessThanToken, SyntaxKind.CommaToken) &&
token.Parent.IsKind(SyntaxKind.TypeParameterList))
{
result = new NameDeclarationInfo(
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.TypeParameter)),
Accessibility.NotApplicable,
new DeclarationModifiers(),
type: null,
alias: null);
return true;
}
result = default;
return false;
}
private static bool IsPrimaryConstructorParameter(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<ParameterSyntax>(
token, semanticModel,
p => p.Type,
_ => default,
_ => s_propertySyntaxKind,
cancellationToken);
if (result.Type != null &&
token.GetAncestor<ParameterSyntax>().Parent.IsParentKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration))
{
return true;
}
result = default;
return false;
}
private static bool IsParameterDeclaration(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = IsLastTokenOfType<ParameterSyntax>(
token, semanticModel,
p => p.Type,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
return result.Type != null;
}
private static bool IsPatternMatching(SyntaxToken token, SemanticModel semanticModel,
CancellationToken cancellationToken, out NameDeclarationInfo result)
{
result = default;
if (token.Parent.IsParentKind(SyntaxKind.IsExpression))
{
result = IsLastTokenOfType<BinaryExpressionSyntax>(
token, semanticModel,
b => b.Right,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
}
else if (token.Parent.IsParentKind(SyntaxKind.CaseSwitchLabel))
{
result = IsLastTokenOfType<CaseSwitchLabelSyntax>(
token, semanticModel,
b => b.Value,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
}
else if (token.Parent.IsParentKind(SyntaxKind.DeclarationPattern))
{
result = IsLastTokenOfType<DeclarationPatternSyntax>(
token, semanticModel,
b => b.Type,
_ => default,
_ => s_parameterSyntaxKind,
cancellationToken);
}
return result.Type != null;
}
private static bool IsPossibleTypeToken(SyntaxToken token) =>
token.IsKind(
SyntaxKind.IdentifierToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.CloseBracketToken,
SyntaxKind.QuestionToken)
|| token.Parent.IsKind(SyntaxKind.PredefinedType);
private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleMemberDeclarations(DeclarationModifiers modifiers)
{
if (modifiers.IsConst || modifiers.IsReadOnly)
{
return ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field));
}
var possibleTypes = ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary));
if (modifiers.IsAbstract || modifiers.IsVirtual || modifiers.IsSealed || modifiers.IsOverride)
{
possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field));
}
if (modifiers.IsAsync || modifiers.IsPartial)
{
// Fields and properties cannot be async or partial.
possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field));
possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Property));
}
return possibleTypes;
}
private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleLocalDeclarations(DeclarationModifiers modifiers)
{
return
modifiers.IsConst
? ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)) :
modifiers.IsAsync || modifiers.IsUnsafe
? ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.LocalFunction)) :
ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(MethodKind.LocalFunction));
}
private static DeclarationModifiers GetDeclarationModifiers(SyntaxTokenList modifiers)
{
var declarationModifiers = new DeclarationModifiers();
foreach (var modifer in modifiers)
{
switch (modifer.Kind())
{
case SyntaxKind.StaticKeyword:
declarationModifiers = declarationModifiers.WithIsStatic(true);
continue;
case SyntaxKind.AbstractKeyword:
declarationModifiers = declarationModifiers.WithIsAbstract(true);
continue;
case SyntaxKind.NewKeyword:
declarationModifiers = declarationModifiers.WithIsNew(true);
continue;
case SyntaxKind.UnsafeKeyword:
declarationModifiers = declarationModifiers.WithIsUnsafe(true);
continue;
case SyntaxKind.ReadOnlyKeyword:
declarationModifiers = declarationModifiers.WithIsReadOnly(true);
continue;
case SyntaxKind.VirtualKeyword:
declarationModifiers = declarationModifiers.WithIsVirtual(true);
continue;
case SyntaxKind.OverrideKeyword:
declarationModifiers = declarationModifiers.WithIsOverride(true);
continue;
case SyntaxKind.SealedKeyword:
declarationModifiers = declarationModifiers.WithIsSealed(true);
continue;
case SyntaxKind.ConstKeyword:
declarationModifiers = declarationModifiers.WithIsConst(true);
continue;
case SyntaxKind.AsyncKeyword:
declarationModifiers = declarationModifiers.WithAsync(true);
continue;
case SyntaxKind.PartialKeyword:
declarationModifiers = declarationModifiers.WithPartial(true);
continue;
}
}
return declarationModifiers;
}
private static Accessibility? GetAccessibility(SyntaxTokenList modifiers)
{
for (var i = modifiers.Count - 1; i >= 0; i--)
{
var modifier = modifiers[i];
switch (modifier.Kind())
{
case SyntaxKind.PrivateKeyword:
return Accessibility.Private;
case SyntaxKind.PublicKeyword:
return Accessibility.Public;
case SyntaxKind.ProtectedKeyword:
return Accessibility.Protected;
case SyntaxKind.InternalKeyword:
return Accessibility.Internal;
}
}
return null;
}
private static SyntaxNode GetNodeDenotingTheTypeOfTupleArgument(ArgumentSyntax argumentSyntax)
{
switch (argumentSyntax.Expression?.Kind())
{
case SyntaxKind.DeclarationExpression:
// The parser found a declaration as in (System.Action action, System.Array a$$)
// we need the type part of the declaration expression.
return ((DeclarationExpressionSyntax)argumentSyntax.Expression).Type;
default:
// We assume the parser found something that represents something named,
// e.g. a MemberAccessExpression as in (System.Action action, System.Array $$)
// We also assume that this name could be resolved to a type.
return argumentSyntax.Expression;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IBidirectionalMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Roslyn.Utilities
{
internal interface IBidirectionalMap<TKey, TValue>
{
bool IsEmpty { get; }
bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value);
bool TryGetKey(TValue value, [MaybeNullWhen(false)] out TKey key);
TValue? GetValueOrDefault(TKey key);
TKey? GetKeyOrDefault(TValue value);
bool ContainsKey(TKey key);
bool ContainsValue(TValue value);
IBidirectionalMap<TKey, TValue> RemoveKey(TKey key);
IBidirectionalMap<TKey, TValue> RemoveValue(TValue value);
IBidirectionalMap<TKey, TValue> Add(TKey key, TValue value);
IEnumerable<TKey> Keys { get; }
IEnumerable<TValue> Values { 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 System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Roslyn.Utilities
{
internal interface IBidirectionalMap<TKey, TValue>
{
bool IsEmpty { get; }
bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value);
bool TryGetKey(TValue value, [MaybeNullWhen(false)] out TKey key);
TValue? GetValueOrDefault(TKey key);
TKey? GetKeyOrDefault(TValue value);
bool ContainsKey(TKey key);
bool ContainsValue(TValue value);
IBidirectionalMap<TKey, TValue> RemoveKey(TKey key);
IBidirectionalMap<TKey, TValue> RemoveValue(TValue value);
IBidirectionalMap<TKey, TValue> Add(TKey key, TValue value);
IEnumerable<TKey> Keys { get; }
IEnumerable<TValue> Values { get; }
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptInlineRenameReplacementKindHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
internal static class VSTypeScriptInlineRenameReplacementKindHelpers
{
public static VSTypeScriptInlineRenameReplacementKind ConvertFrom(InlineRenameReplacementKind kind)
{
return kind switch
{
InlineRenameReplacementKind.NoConflict => VSTypeScriptInlineRenameReplacementKind.NoConflict,
InlineRenameReplacementKind.ResolvedReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict,
InlineRenameReplacementKind.ResolvedNonReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict,
InlineRenameReplacementKind.UnresolvedConflict => VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict,
InlineRenameReplacementKind.Complexified => VSTypeScriptInlineRenameReplacementKind.Complexified,
_ => throw ExceptionUtilities.UnexpectedValue(kind),
};
}
public static InlineRenameReplacementKind ConvertTo(VSTypeScriptInlineRenameReplacementKind kind)
{
return kind switch
{
VSTypeScriptInlineRenameReplacementKind.NoConflict => InlineRenameReplacementKind.NoConflict,
VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict => InlineRenameReplacementKind.ResolvedReferenceConflict,
VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict => InlineRenameReplacementKind.ResolvedNonReferenceConflict,
VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict => InlineRenameReplacementKind.UnresolvedConflict,
VSTypeScriptInlineRenameReplacementKind.Complexified => InlineRenameReplacementKind.Complexified,
_ => throw ExceptionUtilities.UnexpectedValue(kind),
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
internal static class VSTypeScriptInlineRenameReplacementKindHelpers
{
public static VSTypeScriptInlineRenameReplacementKind ConvertFrom(InlineRenameReplacementKind kind)
{
return kind switch
{
InlineRenameReplacementKind.NoConflict => VSTypeScriptInlineRenameReplacementKind.NoConflict,
InlineRenameReplacementKind.ResolvedReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict,
InlineRenameReplacementKind.ResolvedNonReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict,
InlineRenameReplacementKind.UnresolvedConflict => VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict,
InlineRenameReplacementKind.Complexified => VSTypeScriptInlineRenameReplacementKind.Complexified,
_ => throw ExceptionUtilities.UnexpectedValue(kind),
};
}
public static InlineRenameReplacementKind ConvertTo(VSTypeScriptInlineRenameReplacementKind kind)
{
return kind switch
{
VSTypeScriptInlineRenameReplacementKind.NoConflict => InlineRenameReplacementKind.NoConflict,
VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict => InlineRenameReplacementKind.ResolvedReferenceConflict,
VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict => InlineRenameReplacementKind.ResolvedNonReferenceConflict,
VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict => InlineRenameReplacementKind.UnresolvedConflict,
VSTypeScriptInlineRenameReplacementKind.Complexified => InlineRenameReplacementKind.Complexified,
_ => throw ExceptionUtilities.UnexpectedValue(kind),
};
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/CodeLens/CodeLensCallbackListener.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeLens;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Language.CodeLens;
using Microsoft.VisualStudio.Language.CodeLens.Remoting;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Settings;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.CodeLens
{
/// <summary>
/// This is used by new codelens API to get extra data from VS if it is needed.
/// </summary>
[Export(typeof(ICodeLensCallbackListener))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
internal class CodeLensCallbackListener : ICodeLensCallbackListener, ICodeLensContext
{
private const int DefaultMaxSearchResultsValue = 99;
private const string CodeLensUserSettingsConfigPath = @"Text Editor\Global Options";
private const string CodeLensMaxSearchResults = nameof(CodeLensMaxSearchResults);
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly IServiceProvider _serviceProvider;
private readonly IThreadingContext _threadingContext;
private int _maxSearchResults = int.MinValue;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CodeLensCallbackListener(
IThreadingContext threadingContext,
SVsServiceProvider serviceProvider,
VisualStudioWorkspaceImpl workspace)
{
_threadingContext = threadingContext;
_serviceProvider = serviceProvider;
_workspace = workspace;
}
public async Task<ImmutableDictionary<Guid, string>> GetProjectVersionsAsync(ImmutableArray<Guid> projectGuids, CancellationToken cancellationToken)
{
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
var builder = ImmutableDictionary.CreateBuilder<Guid, string>();
var solution = _workspace.CurrentSolution;
foreach (var project in solution.Projects)
{
var projectGuid = _workspace.GetProjectGuid(project.Id);
if (!projectGuids.Contains(projectGuid))
continue;
var projectVersion = await service.GetProjectCodeLensVersionAsync(solution, project.Id, cancellationToken).ConfigureAwait(false);
builder[projectGuid] = projectVersion.ToString();
}
return builder.ToImmutable();
}
public async Task<ReferenceCount?> GetReferenceCountAsync(
CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, ReferenceCount? previousCount, CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var (documentId, node) = await GetDocumentIdAndNodeAsync(
solution, descriptor, descriptorContext.ApplicableSpan, cancellationToken).ConfigureAwait(false);
if (documentId == null)
{
return null;
}
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
if (previousCount is not null)
{
// Avoid calculating results if we already have a result for the current project version
var currentProjectVersion = await service.GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false);
if (previousCount.Value.Version == currentProjectVersion.ToString())
{
return previousCount;
}
}
var maxSearchResults = await GetMaxResultCapAsync(cancellationToken).ConfigureAwait(false);
return await service.GetReferenceCountAsync(solution, documentId, node, maxSearchResults, cancellationToken).ConfigureAwait(false);
}
public async Task<(string projectVersion, ImmutableArray<ReferenceLocationDescriptor> references)?> FindReferenceLocationsAsync(
CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var (documentId, node) = await GetDocumentIdAndNodeAsync(
solution, descriptor, descriptorContext.ApplicableSpan, cancellationToken).ConfigureAwait(false);
if (documentId == null)
{
return null;
}
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
var references = await service.FindReferenceLocationsAsync(solution, documentId, node, cancellationToken).ConfigureAwait(false);
if (!references.HasValue)
{
return null;
}
var projectVersion = await service.GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false);
return (projectVersion.ToString(), references.Value);
}
public async Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(
CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var (documentId, node) = await GetDocumentIdAndNodeAsync(
solution, descriptor, descriptorContext.ApplicableSpan, cancellationToken).ConfigureAwait(false);
if (documentId == null)
{
return null;
}
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
return await service.FindReferenceMethodsAsync(solution, documentId, node, cancellationToken).ConfigureAwait(false);
}
private async Task<(DocumentId?, SyntaxNode?)> GetDocumentIdAndNodeAsync(
Solution solution, CodeLensDescriptor descriptor, Span? span, CancellationToken cancellationToken)
{
if (span is null)
{
return default;
}
if (!TryGetDocument(solution, descriptor.ProjectGuid, descriptor.FilePath, out var document))
{
return default;
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var textSpan = span.Value.ToTextSpan();
// TODO: This check avoids ArgumentOutOfRangeException but it's not clear if this is the right solution
// https://github.com/dotnet/roslyn/issues/44639
if (!root.FullSpan.Contains(textSpan))
{
return default;
}
return (document.Id, root.FindNode(textSpan));
}
private async Task<int> GetMaxResultCapAsync(CancellationToken cancellationToken)
{
await EnsureMaxResultAsync(cancellationToken).ConfigureAwait(false);
return _maxSearchResults;
}
private async Task EnsureMaxResultAsync(CancellationToken cancellationToken)
{
if (_maxSearchResults != int.MinValue)
{
return;
}
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
var settingsManager = new ShellSettingsManager(_serviceProvider);
var settingsStore = settingsManager.GetReadOnlySettingsStore(Settings.SettingsScope.UserSettings);
try
{
// If 14.0\Text Editor\Global Options\CodeLensMaxSearchResults
// exists
// as a value other than Int 32 - disable the capping feature.
// exists
// as Int32 with value <= 0 - disable the feature
// as Int32 with value > 0 - enable the feature, cap at given `value`.
// does not exist
// - feature is on by default, cap at 99
_maxSearchResults = settingsStore.GetInt32(CodeLensUserSettingsConfigPath, CodeLensMaxSearchResults, defaultValue: DefaultMaxSearchResultsValue);
}
catch (ArgumentException)
{
// guard against users possibly creating a value with datatype other than Int32
_maxSearchResults = DefaultMaxSearchResultsValue;
}
}
private bool TryGetDocument(Solution solution, Guid projectGuid, string filePath, [NotNullWhen(true)] out Document? document)
{
document = null;
if (projectGuid == VSConstants.CLSID.MiscellaneousFilesProject_guid)
{
return false;
}
foreach (var candidateId in solution.GetDocumentIdsWithFilePath(filePath))
{
if (_workspace.GetProjectGuid(candidateId.ProjectId) == projectGuid)
{
var currentContextId = _workspace.GetDocumentIdInCurrentContext(candidateId);
document = solution.GetDocument(currentContextId);
break;
}
}
return document != 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.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeLens;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Language.CodeLens;
using Microsoft.VisualStudio.Language.CodeLens.Remoting;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Settings;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.CodeLens
{
/// <summary>
/// This is used by new codelens API to get extra data from VS if it is needed.
/// </summary>
[Export(typeof(ICodeLensCallbackListener))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
internal class CodeLensCallbackListener : ICodeLensCallbackListener, ICodeLensContext
{
private const int DefaultMaxSearchResultsValue = 99;
private const string CodeLensUserSettingsConfigPath = @"Text Editor\Global Options";
private const string CodeLensMaxSearchResults = nameof(CodeLensMaxSearchResults);
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly IServiceProvider _serviceProvider;
private readonly IThreadingContext _threadingContext;
private int _maxSearchResults = int.MinValue;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CodeLensCallbackListener(
IThreadingContext threadingContext,
SVsServiceProvider serviceProvider,
VisualStudioWorkspaceImpl workspace)
{
_threadingContext = threadingContext;
_serviceProvider = serviceProvider;
_workspace = workspace;
}
public async Task<ImmutableDictionary<Guid, string>> GetProjectVersionsAsync(ImmutableArray<Guid> projectGuids, CancellationToken cancellationToken)
{
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
var builder = ImmutableDictionary.CreateBuilder<Guid, string>();
var solution = _workspace.CurrentSolution;
foreach (var project in solution.Projects)
{
var projectGuid = _workspace.GetProjectGuid(project.Id);
if (!projectGuids.Contains(projectGuid))
continue;
var projectVersion = await service.GetProjectCodeLensVersionAsync(solution, project.Id, cancellationToken).ConfigureAwait(false);
builder[projectGuid] = projectVersion.ToString();
}
return builder.ToImmutable();
}
public async Task<ReferenceCount?> GetReferenceCountAsync(
CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, ReferenceCount? previousCount, CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var (documentId, node) = await GetDocumentIdAndNodeAsync(
solution, descriptor, descriptorContext.ApplicableSpan, cancellationToken).ConfigureAwait(false);
if (documentId == null)
{
return null;
}
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
if (previousCount is not null)
{
// Avoid calculating results if we already have a result for the current project version
var currentProjectVersion = await service.GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false);
if (previousCount.Value.Version == currentProjectVersion.ToString())
{
return previousCount;
}
}
var maxSearchResults = await GetMaxResultCapAsync(cancellationToken).ConfigureAwait(false);
return await service.GetReferenceCountAsync(solution, documentId, node, maxSearchResults, cancellationToken).ConfigureAwait(false);
}
public async Task<(string projectVersion, ImmutableArray<ReferenceLocationDescriptor> references)?> FindReferenceLocationsAsync(
CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var (documentId, node) = await GetDocumentIdAndNodeAsync(
solution, descriptor, descriptorContext.ApplicableSpan, cancellationToken).ConfigureAwait(false);
if (documentId == null)
{
return null;
}
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
var references = await service.FindReferenceLocationsAsync(solution, documentId, node, cancellationToken).ConfigureAwait(false);
if (!references.HasValue)
{
return null;
}
var projectVersion = await service.GetProjectCodeLensVersionAsync(solution, documentId.ProjectId, cancellationToken).ConfigureAwait(false);
return (projectVersion.ToString(), references.Value);
}
public async Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(
CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var (documentId, node) = await GetDocumentIdAndNodeAsync(
solution, descriptor, descriptorContext.ApplicableSpan, cancellationToken).ConfigureAwait(false);
if (documentId == null)
{
return null;
}
var service = _workspace.Services.GetRequiredService<ICodeLensReferencesService>();
return await service.FindReferenceMethodsAsync(solution, documentId, node, cancellationToken).ConfigureAwait(false);
}
private async Task<(DocumentId?, SyntaxNode?)> GetDocumentIdAndNodeAsync(
Solution solution, CodeLensDescriptor descriptor, Span? span, CancellationToken cancellationToken)
{
if (span is null)
{
return default;
}
if (!TryGetDocument(solution, descriptor.ProjectGuid, descriptor.FilePath, out var document))
{
return default;
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var textSpan = span.Value.ToTextSpan();
// TODO: This check avoids ArgumentOutOfRangeException but it's not clear if this is the right solution
// https://github.com/dotnet/roslyn/issues/44639
if (!root.FullSpan.Contains(textSpan))
{
return default;
}
return (document.Id, root.FindNode(textSpan));
}
private async Task<int> GetMaxResultCapAsync(CancellationToken cancellationToken)
{
await EnsureMaxResultAsync(cancellationToken).ConfigureAwait(false);
return _maxSearchResults;
}
private async Task EnsureMaxResultAsync(CancellationToken cancellationToken)
{
if (_maxSearchResults != int.MinValue)
{
return;
}
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
var settingsManager = new ShellSettingsManager(_serviceProvider);
var settingsStore = settingsManager.GetReadOnlySettingsStore(Settings.SettingsScope.UserSettings);
try
{
// If 14.0\Text Editor\Global Options\CodeLensMaxSearchResults
// exists
// as a value other than Int 32 - disable the capping feature.
// exists
// as Int32 with value <= 0 - disable the feature
// as Int32 with value > 0 - enable the feature, cap at given `value`.
// does not exist
// - feature is on by default, cap at 99
_maxSearchResults = settingsStore.GetInt32(CodeLensUserSettingsConfigPath, CodeLensMaxSearchResults, defaultValue: DefaultMaxSearchResultsValue);
}
catch (ArgumentException)
{
// guard against users possibly creating a value with datatype other than Int32
_maxSearchResults = DefaultMaxSearchResultsValue;
}
}
private bool TryGetDocument(Solution solution, Guid projectGuid, string filePath, [NotNullWhen(true)] out Document? document)
{
document = null;
if (projectGuid == VSConstants.CLSID.MiscellaneousFilesProject_guid)
{
return false;
}
foreach (var candidateId in solution.GetDocumentIdsWithFilePath(filePath))
{
if (_workspace.GetProjectGuid(candidateId.ProjectId) == projectGuid)
{
var currentContextId = _workspace.GetDocumentIdInCurrentContext(candidateId);
document = solution.GetDocument(currentContextId);
break;
}
}
return document != null;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Semantic/Semantics/OutVarTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using static Roslyn.Test.Utilities.TestMetadata;
using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.OutVar)]
public class OutVarTests : CompilingTestBase
{
[Fact]
public void OldVersion()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")]
[WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")]
public void DiagnosticsDifferenceBetweenLanguageVersions_01()
{
var text = @"
public class Cls
{
public static void Test1()
{
Test(out int x1);
}
public static void Test2()
{
var x = new Cls(out int x2);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test(out int x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22),
// (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33),
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (var x1, var x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, long x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,28): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, (long x2, byte x3)));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,29): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29),
// (6,38): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38),
// (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,29): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29),
// (6,38): error CS0165: Use of unassigned local variable 'x3'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_05()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2, x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_06()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
Test1(out var (x1));
System.Console.WriteLine(F1);
}
static ref int var(object x)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_07()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, x2: x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2: x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_08()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (ref x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(ref object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (ref x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_09()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, (x2)));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_10()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var ((x1), x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var ((x1), x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_12()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out M1 (x1, x2));
System.Console.WriteLine(F1);
}
static ref int M1(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_13()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(ref var (x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(ref int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(ref var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_14()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(var (x1, x2));
System.Console.WriteLine(F1);
}
static int var(object x1, object x2)
{
F1 = 123;
return 124;
}
static object Test1(int x)
{
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"124
123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_15()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out M1 (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int M1(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_16()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (a: x2, b: x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (a: x2, b: x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name)
{
return GetReferences(tree, name).Single();
}
private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count)
{
var nameRef = GetReferences(tree, name).ToArray();
Assert.Equal(count, nameRef.Length);
return nameRef;
}
internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name);
}
private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == name);
}
private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name)
{
return GetDeclarations(tree, name).Single();
}
internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name)
{
return GetOutVarDeclarations(tree, name).Single();
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name);
}
private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>();
}
private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken);
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration());
}
[Fact]
public void Simple_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
int x2;
Test3(out x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references);
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references);
}
private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references);
}
internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(
SemanticModel model,
DeclarationExpressionSyntax decl,
IdentifierNameSyntax reference)
{
VerifyModelForOutVar(
model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false,
verifyDataFlow: true, references: reference);
}
private static void VerifyModelForOutVar(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool isDelegateCreation,
bool isExecutableCode,
bool isShadowed,
bool verifyDataFlow = true,
LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax);
Assert.NotNull(symbol);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.False(((ILocalSymbol)symbol).IsFixed);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single();
if (isShadowed)
{
Assert.NotEqual(symbol, other);
}
else
{
Assert.Same(symbol, other);
}
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type);
foreach (var reference in references)
{
Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
if (verifyDataFlow)
{
VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol);
}
}
private static void AssertInfoForDeclarationExpressionSyntax(
SemanticModel model,
DeclarationExpressionSyntax decl,
ISymbol expectedSymbol = null,
ITypeSymbol expectedType = null
)
{
var symbolInfo = model.GetSymbolInfo(decl);
Assert.Equal(expectedSymbol, symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl));
var typeInfo = model.GetTypeInfo(decl);
Assert.Equal(expectedType, typeInfo.Type);
// skip cases where operation is not supported
AssertTypeFromOperation(model, expectedType, decl);
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.Equal(expectedType, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl));
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.True(model.GetConversion(decl).IsIdentity);
var typeSyntax = decl.Type;
Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));
ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType();
if (expected?.IsErrorType() != false)
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol);
}
typeInfo = model.GetTypeInfo(typeSyntax);
Assert.Equal(expected, typeInfo.Type);
Assert.Equal(expected, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax));
Assert.True(model.GetConversion(typeSyntax).IsIdentity);
var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false);
Assert.False(conversion.Exists);
Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Null(model.GetDeclaredSymbol(decl));
}
private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl)
{
// see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail
// unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode.
// what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from
// error recovery mode
var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault();
if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true)
{
// invalid syntax case where operation is not supported
return;
}
Assert.Equal(expectedType, model.GetOperation(decl)?.Type);
}
private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol)
{
var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax;
if (dataFlowParent == null)
{
if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax))
{
Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent);
}
return;
}
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
return;
}
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (isExecutableCode)
{
Assert.True(dataFlow.Succeeded);
Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
if (!isDelegateCreation)
{
Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
var flowsIn = FlowsIn(dataFlowParent, decl, references);
Assert.Equal(flowsIn,
dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(flowsIn,
dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(FlowsOut(dataFlowParent, decl, references),
dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(ReadOutside(dataFlowParent, references),
dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(WrittenOutside(dataFlowParent, references),
dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type);
}
private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
Assert.NotEqual(SymbolKind.Field, symbol.Kind);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
if (symbol.Kind == SymbolKind.Local)
{
var local = symbol.GetSymbol<SourceLocalSymbol>();
var parent = local.IdentifierToken.Parent;
Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration()));
if (parent.Kind() == SyntaxKind.VariableDeclarator)
{
var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent;
switch (parent1.Kind())
{
case SyntaxKind.FixedStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.UsingStatement:
break;
default:
Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind());
break;
}
}
}
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl)
{
return (SingleVariableDesignationSyntax)decl.Designation;
}
private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart)
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool IsRead(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left != reference)
{
return true;
}
break;
default:
return true;
}
return false;
}
private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
ForStatementSyntax forStatement;
if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null &&
forStatement.Incrementors.Span.Contains(decl.Position) &&
forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null))
{
return false;
}
var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault();
var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax);
MethodDeclarationSyntax methodDeclParent;
if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" &&
((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null ||
methodDeclParent.Body.Statements.First() != containingReturnOrThrow))
{
return false;
}
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span) &&
(containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) &&
(reference.SpanStart > decl.SpanStart ||
(containingReturnOrThrow == null &&
reference.Ancestors().OfType<DoStatementSyntax>().Join(
decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any())))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsWrite(reference))
{
return true;
}
}
}
return false;
}
private static bool IsWrite(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left == reference)
{
return true;
}
break;
case SyntaxKind.PreIncrementExpression:
case SyntaxKind.PostIncrementExpression:
case SyntaxKind.PreDecrementExpression:
case SyntaxKind.PostDecrementExpression:
return true;
default:
return false;
}
return false;
}
[Fact]
public void Simple_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Int32 x1), x1);
int x2 = 0;
Test3(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out (int, int) x1), x1);
}
static object Test1(out (int, int) x)
{
x = (123, 124);
return null;
}
static void Test2(object x, (int, int) y)
{
System.Console.WriteLine(y);
}
}
namespace System
{
// struct with two values
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}
" + TestResources.NetFX.ValueTuple.tupleattributes_cs;
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1);
}
static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = new System.Collections.Generic.List<System.Int32>();
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, out x1), x1);
}
static object Test1(out int x, out int y)
{
x = 123;
y = 124;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, x1 = 124), x1);
}
static object Test1(out int x, int y)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1, x1 = 124);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y, int z)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), ref x1);
int x2 = 0;
Test3(ref x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, ref int y)
{
System.Console.WriteLine(y);
}
static void Test3(ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), out x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_10()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out dynamic x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int[] x1), x1);
}
static object Test1(out int[] x)
{
x = new [] {123};
return null;
}
static void Test2(object x, int[] y)
{
System.Console.WriteLine(y[0]);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
Test1(out int x1);
Test2(Test1(out int x2),
out int x2);
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS0128: A local variable named 'x1' is already defined in this scope
// Test1(out int x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23),
// (9,29): error CS0128: A local variable named 'x2' is already defined in this scope
// out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13)
);
}
[Fact]
public void Scope_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, object x)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15)
);
}
[Fact]
public void Scope_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out int x1);
System.Console.WriteLine(x1);
}
static object Test1(out int x)
{
x = 1;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out var x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void AttributeArgument_01()
{
var source =
@"
public class X
{
[Test(out var x3)]
[Test(out int x4)]
[Test(p: out var x5)]
[Test(p: out int x6)]
public static void Main()
{
}
}
class Test : System.Attribute
{
public Test(out int p) { p = 100; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (4,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11),
// (4,19): error CS1003: Syntax error, ',' expected
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19),
// (5,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11),
// (5,15): error CS1525: Invalid expression term 'int'
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15),
// (5,19): error CS1003: Syntax error, ',' expected
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19),
// (6,14): error CS1525: Invalid expression term 'out'
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14),
// (6,14): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18),
// (6,22): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22),
// (7,14): error CS1525: Invalid expression term 'out'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14),
// (7,14): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14),
// (7,18): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22),
// (4,15): error CS0103: The name 'var' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15),
// (4,19): error CS0103: The name 'x3' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19),
// (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6),
// (5,19): error CS0103: The name 'x4' does not exist in the current context
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19),
// (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6),
// (6,18): error CS0103: The name 'var' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18),
// (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18),
// (6,22): error CS0103: The name 'x5' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22),
// (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6),
// (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18),
// (7,22): error CS0103: The name 'x6' does not exist in the current context
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22),
// (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6)
);
var tree = compilation.SyntaxTrees.Single();
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
Assert.False(GetOutVarDeclarations(tree, "x4").Any());
Assert.False(GetOutVarDeclarations(tree, "x5").Any());
Assert.False(GetOutVarDeclarations(tree, "x6").Any());
}
[Fact]
public void Scope_Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Scope_Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out int x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
int x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out int x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out int x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out int x7) && x7 > 0)
{
int x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out int x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out int x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out int x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out int x10))
{
int y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out int x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out int x14),
TakeOutParam(out int x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out int x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out int x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out int x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out int x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out int x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Catch_01_ExplicitType()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_03()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Catch_04()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Scope_ConstructorInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
X(byte x)
: this(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: this(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: this(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: this(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: this(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: this(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
X(params object[] x) {}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : this(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : this(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_02()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x)
: base(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: base(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: base(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: base(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: base(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: base(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : base(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : base(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_03()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D
{
public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_04()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D : C
{
public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_05()
{
var source =
@"using System;
class D
{
public D(int o) : this(SpeculateHere)
{
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_06()
{
var source =
@"using System;
class D : C
{
public D(int o) : base(SpeculateHere)
{
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var initializerOperation = model.GetOperation(initializer);
Assert.Null(initializerOperation.Parent.Parent.Parent);
VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @"
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)')
Children(1):
IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5')
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5')
Left:
IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o')
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5')
Left:
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
public void Scope_ConstructorInitializers_07()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x3)
: base(TakeOutParam(3, out var x3))
{}
X(sbyte x)
: base(TakeOutParam(4, out var x4))
{
int x4 = 1;
System.Console.WriteLine(x4);
}
X(ushort x)
: base(TakeOutParam(51, out var x5))
=> Dummy(TakeOutParam(52, out var x5), x5);
X(short x)
: base(out int x6, x6)
{}
X(uint x)
: base(out var x7, x7)
{}
X(int x)
: base(TakeOutParam(out int x8, x8))
{}
X(ulong x)
: base(TakeOutParam(out var x9, x9))
{}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
public Y(out int x, int y) { x = y; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : base(TakeOutParam(3, out var x3))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40),
// (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x4 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13),
// (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// => Dummy(TakeOutParam(52, out var x5), x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39),
// (24,28): error CS0165: Use of unassigned local variable 'x6'
// : base(out int x6, x6)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28),
// (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list.
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28),
// (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20),
// (32,41): error CS0165: Use of unassigned local variable 'x8'
// : base(TakeOutParam(out int x8, x8))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41),
// (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list.
// : base(TakeOutParam(out var x9, x9))
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").Single();
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref);
}
[Fact]
public void Scope_Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
do
{
Dummy(x1);
}
while (TakeOutParam(true, out var x1) && x1);
}
void Test2()
{
do
Dummy(x2);
while (TakeOutParam(true, out var x2) && x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
do
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4);
}
void Test6()
{
do
Dummy(x6);
while (x6 && TakeOutParam(true, out var x6));
}
void Test7()
{
do
{
var x7 = 12;
Dummy(x7);
}
while (TakeOutParam(true, out var x7) && x7);
}
void Test8()
{
do
Dummy(x8);
while (TakeOutParam(true, out var x8) && x8);
System.Console.WriteLine(x8);
}
void Test9()
{
do
{
Dummy(x9);
do
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9); // 2
}
while (TakeOutParam(true, out var x9) && x9);
}
void Test10()
{
do
{
var y10 = 12;
Dummy(y10);
}
while (TakeOutParam(y10, out var x10));
}
//void Test11()
//{
// do
// {
// let y11 = 12;
// Dummy(y11);
// }
// while (TakeOutParam(y11, out var x11));
//}
void Test12()
{
do
var y12 = 12;
while (TakeOutParam(y12, out var x12));
}
//void Test13()
//{
// do
// let y13 = 12;
// while (TakeOutParam(y13, out var x13));
//}
void Test14()
{
do
{
Dummy(x14);
}
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13),
// (14,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19),
// (22,19): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19),
// (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43),
// (32,19): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy(x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19),
// (40,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16),
// (39,19): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19),
// (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17),
// (56,19): error CS0841: Cannot use local variable 'x8' before it is declared
// Dummy(x8);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19),
// (59,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34),
// (66,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19),
// (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9); // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47),
// (68,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23),
// (81,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29),
// (98,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29),
// (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17),
// (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46),
// (112,19): error CS0841: Cannot use local variable 'x14' before it is declared
// Dummy(x14);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[1]);
VerifyNotAnOutLocal(model, x7Ref[0]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[1]);
VerifyNotAnOutLocal(model, y10Ref[0]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
do
{
}
while (TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@"
do {} while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f;
do
{
f = false;
}
while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
do
;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false);
if (f)
{
do
;
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Do_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1)));
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3
--
1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0;
bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0;
void Test72() => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test11(object x11) => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,29): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29),
// (13,67): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67),
// (19,28): error CS0103: The name 'x7' does not exist in the current context
// void Test72() => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool Test11(object x11) => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")]
public void Scope_ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test3()
{
bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0;
f(null);
}
void Test4()
{
bool f (object o) => x4 && TakeOutParam(o, out int x4);
f(null);
}
void Test5()
{
bool f (object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
f(null, null);
}
void Test6()
{
bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
f1(null);
f2(null);
}
void Test7()
{
Dummy(x7, 1);
bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0;
Dummy(x7, 2);
f(null);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
bool f (object o) => TakeOutParam(o, out int x11) &&
x11 > 0;
f(null);
}
void Test12()
{
bool f (object o) => TakeOutParam(o, out int x12) &&
x12 > 0;
var x12 = 11;
Dummy(x12);
f(null);
}
System.Action Test13()
{
return () =>
{
bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0;
f(null);
};
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15),
// (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54),
// (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
// Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").Single();
VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref);
}
[Fact]
public void ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out int x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedLocalFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out var x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void Scope_ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 => TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 => x4 && TakeOutParam(4, out int x4);
bool Test5 => TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 => TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool this[object x11] => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,19): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 => x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19),
// (13,44): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44),
// (19,26): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool this[object x11] => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void ExpressionBodiedProperties_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void Scope_ExpressionStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
Dummy(TakeOutParam(true, out var x1), x1);
{
Dummy(TakeOutParam(true, out var x1), x1);
}
Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ExpressionStatement_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
Test2(Test1(out int x1), x1);
if (test)
{
Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_ExpressionStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ExpressionStatement_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Scope_FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 = x4 && TakeOutParam(4, out int x4);
bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,57): error CS0103: The name 'x8' does not exist in the current context
// bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57),
// (23,19): error CS0103: The name 'x9' does not exist in the current context
// bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReference(tree, "x8");
VerifyModelForOutVar(model, x8Decl);
VerifyNotInScope(model, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReference(tree, "x9");
VerifyNotInScope(model, x9Ref);
VerifyModelForOutVar(model, x9Decl);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_FieldInitializers_02()
{
var source =
@"using static Test;
public enum X
{
Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0,
Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Test72 = x7,
}
class Test
{
public static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,13): error CS0841: Cannot use local variable 'x4' before it is declared
// Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13),
// (9,38): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38),
// (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant
// Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13),
// (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14),
// (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70),
// (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant
// Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14),
// (15,14): error CS0103: The name 'x7' does not exist in the current context
// Test72 = x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14),
// (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant
// Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0')
Locals: Local_1: System.Int32 x3
IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0')
Condition:
IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenTrue:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
WhenFalse:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
const bool Test4 = x4 && TakeOutParam(4, out int x4);
const bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
const bool Test72 = x7 > 2;
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant
// const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24),
// (10,24): error CS0841: Cannot use local variable 'x4' before it is declared
// const bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24),
// (13,49): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49),
// (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant
// const bool Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("X.Test5").WithLocation(12, 24),
// (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25),
// (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73),
// (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant
// const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// const bool Test72 = x7 > 2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_FieldInitializers_04()
{
var source =
@"
class X : Y
{
public static void Main()
{
}
bool Test3 = TakeOutParam(out int x3, x3);
bool Test4 = TakeOutParam(out var x4, x4);
bool Test5 = TakeOutParam(out int x5, 5);
X()
: this(x5)
{
System.Console.WriteLine(x5);
}
X(object x)
: base(x5)
=> System.Console.WriteLine(x5);
static bool Test6 = TakeOutParam(out int x6, 6);
static X()
{
System.Console.WriteLine(x6);
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
class Y
{
public Y(object y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,43): error CS0165: Use of unassigned local variable 'x3'
// bool Test3 = TakeOutParam(out int x3, x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43),
// (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list.
// bool Test4 = TakeOutParam(out var x4, x4);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43),
// (15,12): error CS0103: The name 'x5' does not exist in the current context
// : this(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12),
// (17,34): error CS0103: The name 'x5' does not exist in the current context
// System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34),
// (21,12): error CS0103: The name 'x5' does not exist in the current context
// : base(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12),
// (22,33): error CS0103: The name 'x5' does not exist in the current context
// => System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33),
// (27,34): error CS0103: The name 'x6' does not exist in the current context
// System.Console.WriteLine(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(4, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
VerifyNotInScope(model, x5Ref[3]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")]
public void FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1);
static bool Dummy(System.Func<int> x)
{
System.Console.WriteLine(x());
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void FieldInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void FieldInitializers_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,54): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void FieldInitializers_06()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void Scope_Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p = Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p = Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* x1 =
Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2),
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p = Dummy(TakeOutParam(true, out var x3) && x3))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4),
p2 = Dummy(TakeOutParam(true, out var x4) && x4))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (14,66): error CS0165: Use of unassigned local variable 'x1'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2 = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Scope_For_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;
Dummy(TakeOutParam(true, out var x1) && x1)
;)
{
Dummy(x1);
}
}
void Test2()
{
for (;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;
Dummy(TakeOutParam(true, out var x4) && x4)
;)
Dummy(x4);
}
void Test6()
{
for (;
Dummy(x6 && TakeOutParam(true, out var x6))
;)
Dummy(x6);
}
void Test7()
{
for (;
Dummy(TakeOutParam(true, out var x7) && x7)
;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;
Dummy(TakeOutParam(true, out var x8) && x8)
;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;
Dummy(TakeOutParam(true, out var x9) && x9)
;)
{
Dummy(x9);
for (;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;)
Dummy(x9);
}
}
void Test10()
{
for (;
Dummy(TakeOutParam(y10, out var x10))
;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;
// Dummy(TakeOutParam(y11, out var x11))
// ;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;
Dummy(TakeOutParam(y12, out var x12))
;)
var y12 = 12;
}
//void Test13()
//{
// for (;
// Dummy(TakeOutParam(y13, out var x13))
// ;)
// let y13 = 12;
//}
void Test14()
{
for (;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(TakeOutParam(true, out var x1) && x1)
)
{
Dummy(x1);
}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2)
)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;;
Dummy(TakeOutParam(true, out var x4) && x4)
)
Dummy(x4);
}
void Test6()
{
for (;;
Dummy(x6 && TakeOutParam(true, out var x6))
)
Dummy(x6);
}
void Test7()
{
for (;;
Dummy(TakeOutParam(true, out var x7) && x7)
)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;;
Dummy(TakeOutParam(true, out var x8) && x8)
)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;;
Dummy(TakeOutParam(true, out var x9) && x9)
)
{
Dummy(x9);
for (;;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
)
Dummy(x9);
}
}
void Test10()
{
for (;;
Dummy(TakeOutParam(y10, out var x10))
)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;;
// Dummy(TakeOutParam(y11, out var x11))
// )
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;;
Dummy(TakeOutParam(y12, out var x12))
)
var y12 = 12;
}
//void Test13()
//{
// for (;;
// Dummy(TakeOutParam(y13, out var x13))
// )
// let y13 = 12;
//}
void Test14()
{
for (;;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (16,19): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19),
// (25,19): error CS0103: The name 'x2' does not exist in the current context
// Dummy(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (44,19): error CS0103: The name 'x6' does not exist in the current context
// Dummy(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19),
// (63,19): error CS0103: The name 'x8' does not exist in the current context
// Dummy(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (74,19): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19),
// (78,23): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23),
// (71,14): warning CS0162: Unreachable code detected
// Dummy(TakeOutParam(true, out var x9) && x9)
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44),
// (128,19): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref[0]);
VerifyNotInScope(model, x2Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref[0]);
VerifyNotInScope(model, x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0]);
VerifyNotInScope(model, x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyNotInScope(model, x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyNotInScope(model, x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
VerifyNotInScope(model, x14Ref[1]);
}
[Fact]
public void Scope_For_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (var b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (var b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (var b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (var b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (var b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (var b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (var b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (var b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (var b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (var b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (var b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (var b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (bool b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (bool b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (bool b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (bool b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (bool b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (bool b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var x1 =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{}
}
void Test2()
{
for (var x2 = true;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
{}
}
void Test3()
{
for (var x3 = true;;
Dummy(TakeOutParam(true, out var x3) && x3)
)
{}
}
void Test4()
{
for (bool x4 =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
{}
}
void Test5()
{
for (bool x5 = true;
Dummy(TakeOutParam(true, out var x5) && x5)
;)
{}
}
void Test6()
{
for (bool x6 = true;;
Dummy(TakeOutParam(true, out var x6) && x6)
)
{}
}
void Test7()
{
for (bool x7 = true, b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{}
}
void Test8()
{
for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8),
b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2 = Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
void Test10()
{
for (var b = x10;
Dummy(TakeOutParam(true, out var x10) && x10) &&
Dummy(TakeOutParam(true, out var x10) && x10);
Dummy(TakeOutParam(true, out var x10) && x10))
{}
}
void Test11()
{
for (bool b = x11;
Dummy(TakeOutParam(true, out var x11) && x11) &&
Dummy(TakeOutParam(true, out var x11) && x11);
Dummy(TakeOutParam(true, out var x11) && x11))
{}
}
void Test12()
{
for (Dummy(x12);
Dummy(x12) &&
Dummy(TakeOutParam(true, out var x12) && x12);
Dummy(TakeOutParam(true, out var x12) && x12))
{}
}
void Test13()
{
for (var b = x13;
Dummy(x13);
Dummy(TakeOutParam(true, out var x13) && x13),
Dummy(TakeOutParam(true, out var x13) && x13))
{}
}
void Test14()
{
for (bool b = x14;
Dummy(x14);
Dummy(TakeOutParam(true, out var x14) && x14),
Dummy(TakeOutParam(true, out var x14) && x14))
{}
}
void Test15()
{
for (Dummy(x15);
Dummy(x15);
Dummy(x15),
Dummy(TakeOutParam(true, out var x15) && x15))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47),
// (13,54): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54),
// (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x2) && x2)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47),
// (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used
// for (var x2 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3) && x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used
// for (var x3 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18),
// (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47),
// (37,54): error CS0165: Use of unassigned local variable 'x4'
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54),
// (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x5) && x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47),
// (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used
// for (bool x5 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19),
// (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x6) && x6)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47),
// (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used
// for (bool x6 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19),
// (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47),
// (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52),
// (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47),
// (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47),
// (77,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23),
// (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47),
// (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47),
// (86,22): error CS0103: The name 'x10' does not exist in the current context
// for (var b = x10;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22),
// (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope
// Dummy(TakeOutParam(true, out var x10) && x10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47),
// (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x10) && x10))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47),
// (95,23): error CS0103: The name 'x11' does not exist in the current context
// for (bool b = x11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23),
// (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope
// Dummy(TakeOutParam(true, out var x11) && x11);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47),
// (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x11) && x11))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47),
// (104,20): error CS0103: The name 'x12' does not exist in the current context
// for (Dummy(x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20),
// (105,20): error CS0841: Cannot use local variable 'x12' before it is declared
// Dummy(x12) &&
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20),
// (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x12) && x12))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47),
// (113,22): error CS0103: The name 'x13' does not exist in the current context
// for (var b = x13;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22),
// (114,20): error CS0103: The name 'x13' does not exist in the current context
// Dummy(x13);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20),
// (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope
// Dummy(TakeOutParam(true, out var x13) && x13))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47),
// (122,23): error CS0103: The name 'x14' does not exist in the current context
// for (bool b = x14;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23),
// (123,20): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20),
// (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope
// Dummy(TakeOutParam(true, out var x14) && x14))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47),
// (131,20): error CS0103: The name 'x15' does not exist in the current context
// for (Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20),
// (132,20): error CS0103: The name 'x15' does not exist in the current context
// Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20),
// (133,20): error CS0841: Cannot use local variable 'x15' before it is declared
// Dummy(x15),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(3, x10Decl.Length);
Assert.Equal(4, x10Ref.Length);
VerifyNotInScope(model, x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]);
VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]);
var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Decl.Length);
Assert.Equal(4, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]);
VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]);
var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Decl.Length);
Assert.Equal(4, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]);
VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(4, x13Ref.Length);
VerifyNotInScope(model, x13Ref[0]);
VerifyNotInScope(model, x13Ref[1]);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyNotInScope(model, x14Ref[0]);
VerifyNotInScope(model, x14Ref[1]);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(4, x15Ref.Length);
VerifyNotInScope(model, x15Ref[0]);
VerifyNotInScope(model, x15Ref[1]);
VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]);
}
[Fact]
public void Scope_For_07()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(x1),
Dummy(TakeOutParam(true, out var x1) && x1))
{}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2),
Dummy(TakeOutParam(true, out var x2) && x2))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,20): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20),
// (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2) && x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
}
[Fact]
public void For_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_03()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_04()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_05()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 10
3 20
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(5, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_06()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)))
{
x0++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"20
30
--
20
30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_07()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
--
10
20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
void Test1()
{
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
void Test15()
{
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60),
// (35,33): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65),
// (68,46): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46),
// (86,46): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,57): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57),
// (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_If_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (TakeOutParam(true, out var x1))
{
Dummy(x1);
}
else
{
System.Console.WriteLine(x1);
}
}
void Test2()
{
if (TakeOutParam(true, out var x2))
Dummy(x2);
else
System.Console.WriteLine(x2);
}
void Test3()
{
if (TakeOutParam(true, out var x3))
Dummy(x3);
else
{
var x3 = 12;
System.Console.WriteLine(x3);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
if (TakeOutParam(true, out var x4))
Dummy(x4);
}
void Test5(int x5)
{
if (TakeOutParam(true, out var x5))
Dummy(x5);
}
void Test6()
{
if (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
if (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
if (TakeOutParam(true, out var x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
if (TakeOutParam(true, out var x9))
{
Dummy(x9);
if (TakeOutParam(true, out var x9)) // 2
Dummy(x9);
}
}
void Test10()
{
if (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
void Test12()
{
if (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// if (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13),
// (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x3 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17),
// (46,40): error CS0128: A local variable named 'x4' is already defined in this scope
// if (TakeOutParam(true, out var x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40),
// (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x5))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40),
// (58,13): error CS0841: Cannot use local variable 'x6' before it is declared
// if (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13),
// (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17),
// (83,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19),
// (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44),
// (91,26): error CS0103: The name 'y10' does not exist in the current context
// if (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26),
// (100,26): error CS0103: The name 'y12' does not exist in the current context
// if (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26),
// (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
}
[Fact]
public void Scope_If_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
if (TakeOutParam(true, out var x1))
{
}
else
{
}
x1++;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_If_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@"
if (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void If_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
Test(2);
}
public static void Test(int val)
{
if (Dummy(val == 1, TakeOutParam(val, out var x1), x1))
{
System.Console.WriteLine(""true"");
System.Console.WriteLine(x1);
}
else
{
System.Console.WriteLine(""false"");
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
true
1
1
2
false
2
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void If_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
;
if (f)
{
if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
System.Action<object> Test1()
{
return (o) => let x1 = o;
}
System.Action<object> Test2()
{
return (o) => let var x2 = o;
}
void Test3()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0));
}
void Test4()
{
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0));
}
void Test6()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0));
}
void Test7()
{
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0),
x7);
Dummy(x7, 2);
}
void Test8()
{
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8));
}
void Test9()
{
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
x9 > 0), x9);
}
void Test10()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
x11 > 0), x11);
}
void Test12()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73),
// (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73),
// (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73),
// (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
[Fact]
public void Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
return l();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
var d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// var d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// var d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
object d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
object d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
object d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
object d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,53): error CS0128: A local variable named 'x4' is already defined in this scope
// object d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53),
// (24,26): error CS0841: Cannot use local variable 'x6' before it is declared
// object d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26),
// (36,50): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var x1 =
Dummy(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
object x2 =
Dummy(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
public void Scope_LocalDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y1 = Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
public void Scope_LocalDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d =TakeOutParam(true, out var x1) && x1 != null;
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
public void LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2);
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (d, dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var (d, dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
var (d, dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var (d, dd, ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,51): error CS0128: A local variable named 'x4' is already defined in this scope
// var (d, dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51),
// (24,24): error CS0841: Cannot use local variable 'x6' before it is declared
// var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
(object d, object dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
(object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
(object d, object dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
(object d, object dd, object ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,61): error CS0128: A local variable named 'x4' is already defined in this scope
// (object d, object dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61),
// (24,34): error CS0841: Cannot use local variable 'x6' before it is declared
// (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (x1, dd) =
(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
(object x2, object dd) =
(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Dummy(x1));
Dummy(x1);
}
void Test2()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2),
Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3),
Dummy(x3));
}
void Test4()
{
(object d1, object d2) = (Dummy(x4),
Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,67): error CS0128: A local variable named 'x1' is already defined in this scope
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67),
// (12,72): error CS0165: Use of unassigned local variable 'x1'
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,41): error CS0841: Cannot use local variable 'x4' before it is declared
// (object d1, object d2) = (Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyNotAnOutLocal(model, x1Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
var (y1, dd) = (TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var (d, dd) = (TakeOutParam(true, out var x1), x1);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
(var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
public void Scope_Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
lock (Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
lock (Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Dummy(x4);
}
void Test6()
{
lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
lock (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
lock (Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
lock (Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
lock (Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// lock (Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
lock (Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// lock (Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
lock (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,48): error CS0128: A local variable named 'x4' is already defined in this scope
// lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48),
// (35,21): error CS0841: Cannot use local variable 'x6' before it is declared
// lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (60,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19),
// (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52),
// (68,34): error CS0103: The name 'y10' does not exist in the current context
// lock (Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34),
// (86,34): error CS0103: The name 'y12' does not exist in the current context
// lock (Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,45): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
if (true)
lock (Dummy(TakeOutParam(true, out var x1)))
{
}
x1++;
}
static object TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Lock_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@"
lock (Dummy(TakeOutParam(true, out var x1), x1)) ;
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
lock (Dummy(TakeOutParam(""lock"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"lock
lock
lock");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static object Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_ParameterDefault_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out int x4))
{}
void Test5(bool p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0')
Locals: Local_1: System.Int32 x3
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0')
Left:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_ParameterDefault_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out var x4))
{}
void Test5(bool p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out var x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
bool Test5 {get;} = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 {get;} = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,25): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,32): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 {get;} = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void PropertyInitializers_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void PropertyInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,63): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void PropertyInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(new X().Test1);
}
int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Scope_Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
}
void Test2()
{
var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
}
void Test3()
{
var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
void Test6()
{
var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
}
void Test7()
{
var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
}
void Test8()
{
var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
}
void Test9()
{
var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
}
void Test10()
{
var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
}
void Test11()
{
var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,26): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26),
// (27,15): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15),
// (35,32): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32),
// (37,15): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15),
// (45,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35),
// (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35),
// (49,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32),
// (49,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36),
// (52,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15),
// (53,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15),
// (61,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35),
// (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35),
// (66,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32),
// (66,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36),
// (69,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15),
// (70,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15),
// (78,26): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26),
// (80,15): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15),
// (87,27): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27),
// (89,27): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27),
// (91,26): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26),
// (91,31): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31),
// (93,15): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15),
// (94,15): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15),
// (102,15): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15),
// (112,25): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25),
// (109,25): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25),
// (114,15): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15),
// (115,15): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15),
// (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24),
// (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
[Fact]
public void Scope_Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35),
// (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35),
// (22,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32),
// (22,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36),
// (25,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15),
// (26,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15),
// (35,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35),
// (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35),
// (40,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32),
// (40,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36),
// (43,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15),
// (44,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0;
var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0);
Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62),
// (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51),
// (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58),
// (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49),
// (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51),
// (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51),
// (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47),
// (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49),
// (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54),
// (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(3, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVarDuplicateInSameScope(model, yDecl);
VerifyNotAnOutLocal(model, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
}
VerifyNotAnOutLocal(model, yRef[2]);
switch (i)
{
case 12:
VerifyNotAnOutLocal(model, yRef[1]);
break;
default:
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
var y13Decl = GetOutVarDeclarations(tree, "y13").Single();
var y13Ref = GetReference(tree, "y13");
VerifyModelForOutVar(model, y13Decl, y13Ref);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_06()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y1),
TakeOutParam(out int y2),
TakeOutParam(out int y3),
TakeOutParam(out int y4),
TakeOutParam(out int y5),
TakeOutParam(out int y6),
TakeOutParam(out int y7),
TakeOutParam(out int y8),
TakeOutParam(out int y9),
TakeOutParam(out int y10),
TakeOutParam(out int y11),
TakeOutParam(out int y12),
from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62),
// (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51),
// (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58),
// (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49),
// (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51),
// (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51),
// (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47),
// (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49),
// (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54),
// (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
break;
case 12:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
}
}
}
[Fact]
public void Scope_Query_07()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y3),
from x1 in new[] { 0 }
select x1
into x1
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on x1 equals x3
select y3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,62): error CS0128: A local variable named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
const string id = "y3";
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
// Since the name is declared twice in the same scope,
// both references are to the same declaration.
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
}
[Fact]
public void Scope_Query_08()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4)
) ? 1 : 0}
from y1 in new[] { 1 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by x1
into y4
select y4;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// from y1 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24),
// (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24),
// (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23),
// (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 5; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_09()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by 1
into y4
select y4 == null ? 1 : 0
into x2
join y5 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4),
TakeOutParam(out var y5)
) ? 1 : 0 }
on x2 equals y5
select x2;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// var res = from y1 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24),
// (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24),
// (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23),
// (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24),
// (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5'
// join y5 in new[] { Dummy(TakeOutParam(out var y1),
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 6; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
switch (i)
{
case 4:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
case 5:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
default:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
[WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void Scope_Query_10()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
select y1;
}
void Test2()
{
var res = from y2 in new[] { 0 }
join x3 in new[] { 1 }
on TakeOutParam(out var y2) ? y2 : 0
equals x3
select y2;
}
void Test3()
{
var res = from x3 in new[] { 0 }
join y3 in new[] { 1 }
on x3
equals TakeOutParam(out var y3) ? y3 : 0
select y3;
}
void Test4()
{
var res = from y4 in new[] { 0 }
where TakeOutParam(out var y4) && y4 == 1
select y4;
}
void Test5()
{
var res = from y5 in new[] { 0 }
orderby TakeOutParam(out var y5) && y5 > 1,
1
select y5;
}
void Test6()
{
var res = from y6 in new[] { 0 }
orderby 1,
TakeOutParam(out var y6) && y6 > 1
select y6;
}
void Test7()
{
var res = from y7 in new[] { 0 }
group TakeOutParam(out var y7) && y7 == 3
by y7;
}
void Test8()
{
var res = from y8 in new[] { 0 }
group y8
by TakeOutParam(out var y8) && y8 == 3;
}
void Test9()
{
var res = from y9 in new[] { 0 }
let x4 = TakeOutParam(out var y9) && y9 > 0
select y9;
}
void Test10()
{
var res = from y10 in new[] { 0 }
select TakeOutParam(out var y10) && y10 > 0;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052
compilation.VerifyDiagnostics(
// (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59),
// (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(out var y2) ? y2 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48),
// (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(out var y3) ? y3 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52),
// (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(out var y4) && y4 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46),
// (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(out var y5) && y5 > 1,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48),
// (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(out var y6) && y6 > 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48),
// (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(out var y7) && y7 == 3
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46),
// (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(out var y8) && y8 == 3;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43),
// (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x4 = TakeOutParam(out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49),
// (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(out var y10) && y10 > 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 11; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(i == 10 ? 1 : 2, yRef.Length);
switch (i)
{
case 4:
case 6:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
case 8:
VerifyModelForOutVar(model, yDecl, yRef[1]);
VerifyNotAnOutLocal(model, yRef[0]);
break;
case 10:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
}
[Fact]
public void Scope_Query_11()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y1),
from x2 in new [] { y1 }
where TakeOutParam(x1, out var y1)
select x2)
select x1;
}
void Test2()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y2),
TakeOutParam(x1 + 1, out var y2))
select x1;
}
void Test3()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out int y3, y3)
select x1;
}
void Test4()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out var y4, y4)
select x1;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(x1, out var y1)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62),
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal(2, y1Decl.Length);
VerifyModelForOutVar(model, y1Decl[0], y1Ref);
VerifyModelForOutVar(model, y1Decl[1]);
var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray();
Assert.Equal(2, y2Decl.Length);
VerifyModelForOutVar(model, y2Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").Single();
VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").Single();
VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0}
on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0
equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0
where TakeOutParam(6, out var y6) && Print(y6)
orderby TakeOutParam(7, out var y7) && Print(y7),
TakeOutParam(8, out var y8) && Print(y8)
group TakeOutParam(9, out var y9) && Print(y9)
by TakeOutParam(10, out var y10) && Print(y10)
into g
let x11 = TakeOutParam(11, out var y11) && Print(y11)
select TakeOutParam(12, out var y12) && Print(y12);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"1
3
5
2
4
6
7
8
10
9
11
12
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl, yRef);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString());
}
}
[Fact]
public void Query_02()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutVar(model, yDecl, yRef);
}
[Fact]
public void Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in new[] { true }
select a && TakeOutParam(3, out int x1) || x1 > 0;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,62): error CS0165: Use of unassigned local variable 'x1'
// select a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
compilation.VerifyOperationTree(x1Decl, expectedOperationTree:
@"
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
");
}
[Fact]
public void Query_04()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static int Test1()
{
var res = from a in new[] { 1 }
select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
return res.Single();
}
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in (new[] { 1 }).AsQueryable()
select TakeOutParam(a, out int x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,46): error CS8198: An expression tree may not contain an out argument variable declaration.
// select TakeOutParam(a, out int x1);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46)
);
}
[Fact]
public void Scope_ReturnStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null; }
object Test1()
{
return Dummy(TakeOutParam(true, out var x1), x1);
{
return Dummy(TakeOutParam(true, out var x1), x1);
}
return Dummy(TakeOutParam(true, out var x1), x1);
}
object Test2()
{
return Dummy(x2, TakeOutParam(true, out var x2));
}
object Test3(int x3)
{
return Dummy(TakeOutParam(true, out var x3), x3);
}
object Test4()
{
var x4 = 11;
Dummy(x4);
return Dummy(TakeOutParam(true, out var x4), x4);
}
object Test5()
{
return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//object Test6()
//{
// let x6 = 11;
// Dummy(x6);
// return Dummy(TakeOutParam(true, out var x6), x6);
//}
//object Test7()
//{
// return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
object Test8()
{
return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
object Test9(bool y9)
{
if (y9)
return Dummy(TakeOutParam(true, out var x9), x9);
return null;
}
System.Func<object> Test10(bool y10)
{
return () =>
{
if (y10)
return Dummy(TakeOutParam(true, out var x10), x10);
return null;};
}
object Test11()
{
Dummy(x11);
return Dummy(TakeOutParam(true, out var x11), x11);
}
object Test12()
{
return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53),
// (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49),
// (14,13): warning CS0162: Unreachable code detected
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13),
// (21,22): error CS0841: Cannot use local variable 'x2' before it is declared
// return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22),
// (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49),
// (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ReturnStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
int Dummy(params object[] x) { return 0;}
int Test1(bool val)
{
if (val)
return Dummy(TakeOutParam(true, out var x1));
x1++;
return 0;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ReturnStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@"
return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Return_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static object Test()
{
return Dummy(TakeOutParam(""return"", out var x1), x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"return");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Return_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static object Test(bool val)
{
if (val)
return Dummy(TakeOutParam(""return 1"", out var x2), x2);
if (!val)
{
return Dummy(TakeOutParam(""return 2"", out var x2), x2);
}
return null;
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"return 1
return 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
switch (TakeOutParam(1, out var x1) ? x1 : 0)
{
case 0:
Dummy(x1, 0);
break;
}
Dummy(x1, 1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
switch (TakeOutParam(4, out var x4) ? x4 : 0)
{
case 4:
Dummy(x4);
break;
}
}
void Test5(int x5)
{
switch (TakeOutParam(5, out var x5) ? x5 : 0)
{
case 5:
Dummy(x5);
break;
}
}
void Test6()
{
switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
{
case 6:
Dummy(x6);
break;
}
}
void Test7()
{
switch (TakeOutParam(7, out var x7) ? x7 : 0)
{
case 7:
var x7 = 12;
Dummy(x7);
break;
}
}
void Test9()
{
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 0);
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 1);
break;
}
break;
}
}
void Test10()
{
switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
{
case 10:
var y10 = 12;
Dummy(y10);
break;
}
}
//void Test11()
//{
// switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0))
// {
// case 11:
// let y11 = 12;
// Dummy(y11);
// break;
// }
//}
void Test14()
{
switch (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14) ? 1 : 0)
{
case 0:
Dummy(x14);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (27,41): error CS0128: A local variable named 'x4' is already defined in this scope
// switch (TakeOutParam(4, out var x4) ? x4 : 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41),
// (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(5, out var x5) ? x5 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41),
// (47,17): error CS0841: Cannot use local variable 'x6' before it is declared
// switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17),
// (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21),
// (71,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9, 0);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23),
// (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(9, out var x9) ? x9 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49),
// (85,17): error CS0103: The name 'y10' does not exist in the current context
// switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17),
// (108,43): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
switch (TakeOutParam(1, out var x1) ? 1 : 0)
{
case 0:
break;
}
Dummy(x1, 1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,15): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Switch_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@"
switch (Dummy(TakeOutParam(true, out var x1), x1)) {}
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test1(0);
Test1(1);
}
static bool Dummy1(bool val, params object[] x) {return val;}
static T Dummy2<T>(T val, params object[] x) {return val;}
static void Test1(int val)
{
switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1)))
{
case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)):
System.Console.WriteLine(x1, y1);
break;
case int z1:
System.Console.WriteLine(x1, z1);
break;
}
System.Console.WriteLine(x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"Test1 case 0
Test1 {0}
Test1 1
Test1 {0}");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 1 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 2 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(TakeOutParam(true, out var x6), x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(TakeOutParam(true, out var x7), x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(TakeOutParam(true, out var x10), x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(TakeOutParam(true, out var x11), x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(TakeOutParam(true, out var x12), x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x15), x15):
case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Dummy(x15);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58),
// (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58),
// (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58),
// (102,95): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95),
// (112,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31),
// (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58),
// (144,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17),
// (146,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31),
// (147,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23),
// (157,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17),
// (162,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31),
// (163,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23),
// (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58),
// (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58),
// (198,58): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58),
// (198,64): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyNotAnOutLocal(model, x4Ref[3]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAnOutLocal(model, x5Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAnOutLocal(model, x9Ref[0]);
VerifyNotAnOutLocal(model, x9Ref[1]);
VerifyNotAnOutLocal(model, x9Ref[2]);
VerifyNotAnOutLocal(model, x9Ref[3]);
VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_03()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
while (TakeOutParam(x1, out var y1) && Print(y1)) break;
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_04()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
do
val = 0;
while (TakeOutParam(x1, out var y1) && Print(y1));
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_05()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
lock ((object)TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_06()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
if (TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
switch (TakeOutParam(x1, out var y1))
{
default: break;
}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_08()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var x in Test(1)) {}
}
static System.Collections.IEnumerable Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
yield return TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_09()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z1 = x1 > 0 & TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_10()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
a: TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (14,1): warning CS0164: This label has not been referenced
// a: TakeOutParam(x1, out var y1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_11()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
return TakeOutParam(x1, out var y1) && Print(y1);
System.Console.WriteLine(y1);
break;
}
return false;
}
static bool Print<T>(T x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (15,17): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_12()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
try
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
throw Dummy(TakeOutParam(x1, out var y1), y1);
System.Console.WriteLine(y1);
break;
}
}
catch
{}
return false;
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (17,21): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_13()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_14()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelPattern_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test8(object val)
{
switch (val)
{
case int x8
when Dummy(x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case int x13 when Dummy(x13):
Dummy(x13);
break;
}
}
void Test14(object val)
{
switch (val)
{
case int x14 when Dummy(x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test16(object val)
{
switch (val)
{
case int x16 when Dummy(x16):
case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Dummy(x16);
break;
}
}
void Test17(object val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x17), x17):
case int x17 when Dummy(x17):
Dummy(x17);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,64): error CS0128: A local variable named 'x8' is already defined in this scope
// when Dummy(x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64),
// (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x13 when Dummy(x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22),
// (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x14 when Dummy(x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22),
// (51,58): error CS0128: A local variable named 'x16' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58),
// (51,64): error CS0165: Use of unassigned local variable 'x16'
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64),
// (62,22): error CS0128: A local variable named 'x17' is already defined in this scope
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22),
// (62,37): error CS0165: Use of unassigned local variable 'x17'
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyNotAnOutLocal(model, x13Ref[3]);
VerifyNotAnOutLocal(model, x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").Single();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(4, x14Ref.Length);
VerifyNotAnOutLocal(model, x14Ref[0]);
VerifyNotAnOutLocal(model, x14Ref[1]);
VerifyNotAnOutLocal(model, x14Ref[2]);
VerifyNotAnOutLocal(model, x14Ref[3]);
VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x16Decl = GetOutVarDeclarations(tree, "x16").Single();
var x16Ref = GetReferences(tree, "x16").ToArray();
Assert.Equal(3, x16Ref.Length);
for (int i = 0; i < x16Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x16Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x16Decl);
var x17Decl = GetOutVarDeclarations(tree, "x17").Single();
var x17Ref = GetReferences(tree, "x17").ToArray();
Assert.Equal(3, x17Ref.Length);
VerifyModelForOutVar(model, x17Decl, x17Ref);
}
[Fact]
public void Scope_ThrowStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1()
{
throw Dummy(TakeOutParam(true, out var x1), x1);
{
throw Dummy(TakeOutParam(true, out var x1), x1);
}
throw Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
throw Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
throw Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
throw Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
throw Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// throw Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// throw Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
throw Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
throw Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
throw Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
throw Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52),
// (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48),
// (21,21): error CS0841: Cannot use local variable 'x2' before it is declared
// throw Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21),
// (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48),
// (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ThrowStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1(bool val)
{
if (val)
throw Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ThrowStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@"
throw Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Throw_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static void Test()
{
try
{
throw Dummy(TakeOutParam(""throw"", out var x2), x2);
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"throw");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
}
[Fact]
public void Throw_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static void Test(bool val)
{
try
{
if (val)
throw Dummy(TakeOutParam(""throw 1"", out var x2), x2);
if (!val)
{
throw Dummy(TakeOutParam(""throw 2"", out var x2), x2);
}
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"throw 1
throw 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49),
// (35,22): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53),
// (68,35): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35),
// (86,35): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (var d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (var d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (var d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72),
// (35,45): error CS0841: Cannot use local variable 'x6' before it is declared
// using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76),
// (68,58): error CS0103: The name 'y10' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58),
// (86,58): error CS0103: The name 'y12' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,69): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,58): error CS0128: A local variable named 'x1' is already defined in this scope
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (12,63): error CS0841: Cannot use local variable 'x1' before it is declared
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63),
// (20,73): error CS0128: A local variable named 'x2' is already defined in this scope
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73),
// (20,78): error CS0165: Use of unassigned local variable 'x2'
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_Using_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void Scope_While_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
while (TakeOutParam(true, out var x1) && x1)
{
Dummy(x1);
}
}
void Test2()
{
while (TakeOutParam(true, out var x2) && x2)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4)
Dummy(x4);
}
void Test6()
{
while (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
while (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
while (TakeOutParam(true, out var x8) && x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
while (TakeOutParam(true, out var x9) && x9)
{
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9) // 2
Dummy(x9);
}
}
void Test10()
{
while (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// while (TakeOutParam(y11, out var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
while (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// while (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
void Test14()
{
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47),
// (68,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29),
// (86,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_While_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
while (TakeOutParam(true, out var x1))
{
;
}
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_While_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@"
while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void While_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
f = false;
f = true;
if (f)
{
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
4");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void While_03()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_05()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
1
2
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Yield_01()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
IEnumerable Test2()
{
yield return Dummy(x2, TakeOutParam(true, out var x2));
}
IEnumerable Test3(int x3)
{
yield return Dummy(TakeOutParam(true, out var x3), x3);
}
IEnumerable Test4()
{
var x4 = 11;
Dummy(x4);
yield return Dummy(TakeOutParam(true, out var x4), x4);
}
IEnumerable Test5()
{
yield return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//IEnumerable Test6()
//{
// let x6 = 11;
// Dummy(x6);
// yield return Dummy(TakeOutParam(true, out var x6), x6);
//}
//IEnumerable Test7()
//{
// yield return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
IEnumerable Test8()
{
yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
IEnumerable Test9(bool y9)
{
if (y9)
yield return Dummy(TakeOutParam(true, out var x9), x9);
}
IEnumerable Test11()
{
Dummy(x11);
yield return Dummy(TakeOutParam(true, out var x11), x11);
}
IEnumerable Test12()
{
yield return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59),
// (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55),
// (23,28): error CS0841: Cannot use local variable 'x2' before it is declared
// yield return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28),
// (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55),
// (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55),
// (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13),
// (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13),
// (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92),
// (72,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_Yield_02()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
IEnumerable Test1()
{
if (true)
yield return TakeOutParam(true, out var x1);
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Yield_03()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
IEnumerable Test1()
{
yield return 0;
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@"
yield return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Yield_01()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
yield return Dummy(TakeOutParam(""yield2"", out var x2), x2);
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2
yield1");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Yield_02()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
bool f = true;
if (f)
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
if (f)
{
yield return Dummy(TakeOutParam(""yield2"", out var x1), x1);
}
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_LabeledStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
a: Dummy(TakeOutParam(true, out var x1), x1);
{
b: Dummy(TakeOutParam(true, out var x1), x1);
}
c: Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
a: Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
a: Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
a: Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
a: Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
//a: Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
//a: Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
a: Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
a: Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
a: Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
a: Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (12,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1),
// (14,1): warning CS0164: This label has not been referenced
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1),
// (16,1): warning CS0164: This label has not been referenced
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (21,1): warning CS0164: This label has not been referenced
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (26,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (33,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (38,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x5), x5);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (59,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1),
// (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1),
// (65,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1),
// (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1),
// (73,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (80,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x11), x11);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1),
// (85,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x12), x12);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_LabeledStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
a: Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1),
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9),
// (13,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_LabeledStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@"
a: b: Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Labeled_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
a: b: c:Test2(Test1(out int x1), x1);
System.Console.Write(x1);
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(
// (11,1): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1),
// (11,4): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4),
// (11,7): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Labeled_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
{
a: Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(
// (15,1): warning CS0164: This label has not been referenced
// a: Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void DataFlow_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
x1);
}
static void Test(out int x, int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
ref x1);
}
static void Test(out int x, ref int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// ref x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
var x2 = 1;
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used
// var x2 = 1;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single();
var dataFlow = model.AnalyzeDataFlow(x2Decl);
Assert.True(dataFlow.Succeeded);
Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString());
Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString());
}
[Fact]
public void TypeMismatch_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
}
static void Test(out short x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short'
// Test(out int x1);
Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(int x1);
Test(ref int x2);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,14): error CS1525: Invalid expression term 'int'
// Test(int x1);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// Test(int x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22),
// (6,18): error CS0103: The name 'x1' does not exist in the current context
// Test(int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18),
// (7,22): error CS0103: The name 'x2' does not exist in the current context
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void Parse_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1.);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,24): error CS1003: Syntax error, ',' expected
// Test(out int x1.);
Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out System.Collections.Generic.IEnumerable<System.Int32>);
}
static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable
// Test(out System.Collections.Generic.IEnumerable<System.Int32>);
Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void GetAliasInfo_01()
{
var text = @"
using a = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out a x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GetAliasInfo_02()
{
var text = @"
using var = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void VarIsNotVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out var x)
{
x = new var() {val = 123};
return null;
}
static void Test2(object x, var y)
{
System.Console.WriteLine(y.val);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void VarIsNotVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test1' does not exist in the current context
// Test1(out var x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9),
// (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0
// public int val;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void SimpleVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static void Test2(object x, object y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0103: The name 'Test1' does not exist in the current context
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
out x1);
}
static object Test1(out int x, out int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// out x1);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
Test1(out x1,
3));
}
static object Test1(out int x, int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// Test1(out x1,
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(ref int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic x = null;
Test2(x.Test1(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x.Test1(out var x1),
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var x1), x1);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new System.Action(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,37): error CS0149: Method name expected
// Test2(new System.Action(out var x1),
Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x, object y)
{
System.Console.WriteLine(y);
}
public Test2()
: this(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : this(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26)
);
var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
var typeInfo = model.GetTypeInfo(initializer);
var symbolInfo = model.GetSymbolInfo(initializer);
var group = model.GetMemberGroup(initializer);
Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936
}
[Fact]
public void ConstructorInitializers_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
public Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}
class Test3 : Test2
{
public Test3()
: base(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : base(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26)
);
}
[Fact]
public void ConstructorInitializers_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
class Test2
{
Test2(out int x)
{
x = 2;
}
public Test2()
: this(out var x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
class Test2
{
public Test2(out int x)
{
x = 1;
}
}
class Test3 : Test2
{
public Test3()
: base(out var x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void ConstructorInitializers_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(System.Func<object> x)
{
System.Console.WriteLine(x());
}
public Test2()
: this(() =>
{
Test1(out var x1);
return x1;
})
{}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (23,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(23, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer();
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular)
.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.True(analyzer.ActionFired);
}
private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer
{
public bool ActionFired { get; private set; }
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.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer);
}
private void Handle(SyntaxNodeAnalysisContext context)
{
ActionFired = true;
var tree = context.Node.SyntaxTree;
var model = context.SemanticModel;
var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent;
SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model);
Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration));
MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration];
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0]));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1]));
}
}
[Fact]
public void ConstructorInitializers_09()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_10()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_11()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (21,37): error CS0165: Use of unassigned local variable 'x1'
// => System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_12()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_13()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_14()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_15()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_16()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_17()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_14()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_15()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var var), var);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var varDecl = GetOutVarDeclaration(tree, "var");
var varRef = GetReferences(tree, "var").Skip(1).Single();
VerifyModelForOutVar(model, varDecl, varRef);
}
[Fact]
public void SimpleVar_16()
{
var text = @"
public class Cls
{
public static void Main()
{
if (Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
static bool Test1(out int x)
{
x = 123;
return true;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void VarAndBetterness_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
Test2(out var x2, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, string y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
static object Test2(out int x, string y)
{
x = 125;
System.Console.WriteLine(x);
return null;
}
static object Test2(out short x, object y)
{
x = 126;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
VerifyModelForOutVar(model, x2Decl);
}
[Fact]
public void VarAndBetterness_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, object y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)'
// Test1(out var x1, null);
Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.ArgIterator x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_03()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async void Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void RestrictedTypes_04()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out System.ArgIterator x1), x1);
var x = default(System.ArgIterator);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
targetFramework: TargetFramework.Mscorlib45,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out System.ArgIterator x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// var x = default(System.ArgIterator);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9),
// (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async void Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ElementAccess_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out var x1]);
Test2(x1);
Test2(x[out var _]);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25),
// (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21),
// (9,21): error CS8183: Cannot infer the type of implicitly-typed discard.
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21)
);
}
[Fact]
public void PointerAccess_01()
{
var text = @"
public class Cls
{
public static unsafe void Main()
{
int* p = (int*)0;
Test2(p[out var x1]);
Test2(x1);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25)
);
}
[Fact]
public void ElementAccess_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out int x1], x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21)
);
}
[Fact]
[WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")]
public void MissingArgumentAndNamedOutVarArgument()
{
var source =
@"class Program
{
public static void Main(string[] args)
{
if (M(s: out var s))
{
string s2 = s;
}
}
public static bool M(int i, out string s)
{
s = i.ToString();
return true;
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)'
// if (M(s: out var s))
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13)
);
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x);
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out int x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
for (var y = Test1(out var x) + x; y != 0 ; y = 0)
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
foreach (var y in new [] {Test1(out var x) + x})
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(x: 1, out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21),
// (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
int x = 0;
Test1(y: ref x, y: out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)'
// Test1(y: ref x, y: out var y);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
var yRef = GetReferences(tree, "y").ToArray();
Assert.Equal(3, yRef.Length);
Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString());
VerifyModelForOutVar(model, yDecl, yRef[2]);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamic()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int z];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1) //z
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}");
}
[Fact]
public void IndexingDynamicWithDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"
{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}
");
}
[Fact]
public void IndexingDynamicWithVarDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef });
comp.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out var _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23)
);
}
[Fact]
public void IndexingDynamicWithShortDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out _];
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutVar()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.True(x1.Type.IsErrorType());
VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var x = d[out var x1] + x1;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutInt()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation.VerifyDiagnostics();
}
[ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void OutVariableDeclarationInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; return 2;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.2
ret
}
// i = 3; return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.3
stind.i4
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 4; return 5;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.5
ret
}
// i = 6; return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.6
stind.i4
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} x1] + "" "" + x1);
ia.P[out {0} x2] = 4;
Console.WriteLine(x2);
Console.WriteLine(ia[out {0} x3] + "" "" + x3);
ia[out {0} x4] = 4;
Console.WriteLine(x4);
}}
}}";
string[] fillIns = new[] { "int", "var" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 });
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString());
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString());
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(1, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString());
CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput:
@"2 1
3
5 4
6")
.VerifyIL("B.Main()",
@"{
// Code size 113 (0x71)
.maxstack 4
.locals init (int V_0, //x1
int V_1, //x2
int V_2, //x3
int V_3, //x4
int V_4)
IL_0000: newobj ""A..ctor()""
IL_0005: dup
IL_0006: ldloca.s V_0
IL_0008: callvirt ""int IA.P[out int].get""
IL_000d: stloc.s V_4
IL_000f: ldloca.s V_4
IL_0011: call ""string int.ToString()""
IL_0016: ldstr "" ""
IL_001b: ldloca.s V_0
IL_001d: call ""string int.ToString()""
IL_0022: call ""string string.Concat(string, string, string)""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: dup
IL_002d: ldloca.s V_1
IL_002f: ldc.i4.4
IL_0030: callvirt ""void IA.P[out int].set""
IL_0035: ldloc.1
IL_0036: call ""void System.Console.WriteLine(int)""
IL_003b: dup
IL_003c: ldloca.s V_2
IL_003e: callvirt ""int IA.this[out int].get""
IL_0043: stloc.s V_4
IL_0045: ldloca.s V_4
IL_0047: call ""string int.ToString()""
IL_004c: ldstr "" ""
IL_0051: ldloca.s V_2
IL_0053: call ""string int.ToString()""
IL_0058: call ""string string.Concat(string, string, string)""
IL_005d: call ""void System.Console.WriteLine(string)""
IL_0062: ldloca.s V_3
IL_0064: ldc.i4.4
IL_0065: callvirt ""void IA.this[out int].set""
IL_006a: ldloc.3
IL_006b: call ""void System.Console.WriteLine(int)""
IL_0070: ret
}");
}
}
[ClrOnlyFact]
public void OutVariableDiscardInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; System.Console.WriteLine(11); return 111;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.s 11
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x06F
ret
}
// i = 2; System.Console.Write(22); return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.2
stind.i4
ldc.i4.s 22
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 3; System.Console.WriteLine(33) return 333;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.3
stind.i4
ldc.i4.s 33
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x14D
ret
}
// i = 4; System.Console.WriteLine(44); return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.s 44
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} _]);
ia.P[out {0} _] = 4;
Console.WriteLine(ia[out {0} _]);
ia[out {0} _] = 4;
}}
}}";
string[] fillIns = new[] { "int", "var", "" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"11
111
22
33
333
44")
.VerifyIL("B.Main()",
@"
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (A V_0, //a
IA V_1, //ia
int V_2)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloca.s V_2
IL_000c: callvirt ""int IA.P[out int].get""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ldloc.1
IL_0018: ldloca.s V_2
IL_001a: ldc.i4.4
IL_001b: callvirt ""void IA.P[out int].set""
IL_0020: nop
IL_0021: ldloc.1
IL_0022: ldloca.s V_2
IL_0024: callvirt ""int IA.this[out int].get""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ldloc.1
IL_0030: ldloca.s V_2
IL_0032: ldc.i4.4
IL_0033: callvirt ""void IA.this[out int].set""
IL_0038: nop
IL_0039: ret
}");
}
}
[Fact]
public void ElementAccess_04()
{
var text = @"
using System.Collections.Generic;
public class Cls
{
public static void Main()
{
var list = new Dictionary<int, long>
{
[out var x1] = 3,
[out var _] = 4,
[out _] = 5
};
System.Console.Write(x1);
System.Console.Write(_);
{
int _ = 1;
var list2 = new Dictionary<int, long> { [out _] = 6 };
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var x1] = 3,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18),
// (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var _] = 4,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18),
// (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out _] = 5
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18),
// (14,30): error CS0103: The name '_' does not exist in the current context
// System.Console.Write(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30),
// (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var list2 = new Dictionary<int, long> { [out _] = 6 };
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58)
);
}
[Fact]
public void ElementAccess_05()
{
var text = @"
public class Cls
{
public static void Main()
{
int[out var x1] a = null; // fatal syntax error - 'out' is skipped
int b(out var x2) = null; // parsed as a local function with syntax error
int c[out var x3] = null; // fatal syntax error - 'out' is skipped
int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
x4 = 0;
}
}";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count());
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
compilation.VerifyDiagnostics(
// (6,13): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13),
// (6,21): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21),
// (7,27): error CS1002: ; expected
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27),
// (7,27): error CS1525: Invalid expression term '='
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27),
// (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14),
// (8,15): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15),
// (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19),
// (8,23): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23),
// (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23),
// (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17),
// (10,17): error CS1003: Syntax error, '[' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17),
// (10,28): error CS1003: Syntax error, ']' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28),
// (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12),
// (6,17): error CS0103: The name 'var' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17),
// (6,21): error CS0103: The name 'x1' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21),
// (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body.
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13),
// (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19),
// (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29),
// (8,19): error CS0103: The name 'var' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19),
// (8,23): error CS0103: The name 'x3' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23),
// (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13),
// (6,25): warning CS0219: The variable 'a' is assigned but its value is never used
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25),
// (10,13): warning CS0168: The variable 'd' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13),
// (10,16): warning CS0168: The variable 'e' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16),
// (7,13): warning CS8321: The local function 'b' is declared but never used
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13)
);
}
[Fact]
public void ElementAccess_06()
{
var text = @"
public class Cls
{
public static void Main()
{
{
int[] e = null;
var z1 = e?[out var x1];
x1 = 1;
}
{
int[][] e = null;
var z2 = e?[out var x2]?[out var x3];
x2 = 1;
x3 = 2;
}
{
int[][] e = null;
var z3 = e?[0]?[out var x4];
x4 = 1;
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var x2Decl = GetOutVarDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29),
// (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33),
// (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29),
// (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'.
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33),
// (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33),
// (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'.
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37)
);
}
[Fact]
public void FixedFieldSize()
{
var text = @"
unsafe struct S
{
fixed int F1[out var x1, x1];
//fixed int F2[3 is int x2 ? x2 : 3];
//fixed int F2[3 is int x3 ? 3 : 3, x3];
}
";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Empty(GetOutVarDeclarations(tree, "x1"));
compilation.VerifyDiagnostics(
// (4,18): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18),
// (4,26): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26),
// (4,17): error CS7092: A fixed buffer may only have one dimension.
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17),
// (4,22): error CS0103: The name 'var' does not exist in the current context
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22)
);
}
[Fact]
public void Scope_DeclaratorArguments_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
int d,e(Dummy(TakeOutParam(true, out var x1), x1));
}
void Test4()
{
var x4 = 11;
Dummy(x4);
int d,e(Dummy(TakeOutParam(true, out var x4), x4));
}
void Test6()
{
int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
}
void Test8()
{
int d,e(Dummy(TakeOutParam(true, out var x8), x8));
System.Console.WriteLine(x8);
}
void Test14()
{
int d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// int d,e(Dummy(TakeOutParam(true, out var x4), x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (30,34): error CS0165: Use of unassigned local variable 'x8'
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl)
{
Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl));
}
private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls)
{
foreach (var decl in decls)
{
AssertContainedInDeclaratorArguments(decl);
}
}
[Fact]
public void Scope_DeclaratorArguments_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d, x1(
Dummy(TakeOutParam(true, out var x1), x1));
Dummy(x1);
}
void Test2()
{
object d, x2(
Dummy(TakeOutParam(true, out var x2), x2));
Dummy(x2);
}
void Test3()
{
object x3, d(
Dummy(TakeOutParam(true, out var x3), x3));
Dummy(x3);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,13): error CS0818: Implicitly-typed variables must be initialized
// var d, x1(
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13),
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (21,15): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15),
// (27,54): error CS0128: A local variable named 'x3' is already defined in this scope
// Dummy(TakeOutParam(true, out var x3), x3));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54),
// (28,15): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1( Dummy(x1));
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2(Dummy(x3));
}
void Test4()
{
object d1,e(Dummy(x4)],
d2(Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1( Dummy(x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (14,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1,e(Dummy(x4)],
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 (Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (13,27): error CS0165: Use of unassigned local variable 'x1'
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59),
// (26,27): error CS0165: Use of unassigned local variable 'x3'
// d2 = Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y, y1(Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single();
Assert.Equal("var y1", y1.ToTestDisplayString());
Assert.True(((ILocalSymbol)y1).Type.IsErrorType());
}
[Fact]
public void Scope_DeclaratorArguments_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d,e(TakeOutParam(true, out var x1) && x1 != null);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13),
// (11,17): error CS0818: Implicitly-typed variables must be initialized
// var d,e(TakeOutParam(true, out var x1) && x1 != null);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e);
Assert.Equal("var e", symbol.ToTestDisplayString());
Assert.True(symbol.Type.IsErrorType());
}
[Fact]
[WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")]
public void Scope_DeclaratorArguments_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)];
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
AssertContainedInDeclaratorArguments(y1Decl);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType());
}
[Fact]
[WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")]
public void Scope_DeclaratorArguments_08()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x1) && x1)
);;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x2) && x2)
);;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool a, b(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
Dummy(x4);
}
void Test6()
{
for (bool a, b(
Dummy(x6 && TakeOutParam(true, out var x6))
);;)
Dummy(x6);
}
void Test7()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x8) && x8)
);;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool a1, b1(
Dummy(TakeOutParam(true, out var x9) && x9)
);;)
{
Dummy(x9);
for (bool a2, b2(
Dummy(TakeOutParam(true, out var x9) && x9) // 2
);;)
Dummy(x9);
}
}
void Test10()
{
for (bool a, b(
Dummy(TakeOutParam(y10, out var x10))
);;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y11, out var x11))
// );;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool a, b(
Dummy(TakeOutParam(y12, out var x12))
);;)
var y12 = 12;
}
//void Test13()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y13, out var x13))
// );;)
// let y13 = 12;
//}
void Test14()
{
for (bool a, b(
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
);;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_09()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
for (bool d, x4(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
{}
}
void Test7()
{
for (bool x7 = true, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{}
}
void Test8()
{
for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)],
b2(Dummy(TakeOutParam(true, out var x8) && x8));
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2(Dummy(TakeOutParam(true, out var x9) && x9));
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47),
// (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47),
// (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used
// for (bool x7 = true, b(
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19),
// (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2(Dummy(TakeOutParam(true, out var x8) && x8));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52),
// (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47),
// (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47),
// (37,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23),
// (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47),
// (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl[0]);
AssertContainedInDeclaratorArguments(x8Decl[1]);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]);
}
[Fact]
public void Scope_DeclaratorArguments_10()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,e(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (var d,e(Dummy(TakeOutParam(true, out var x2), x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Dummy(x4);
}
void Test6()
{
using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d,e(Dummy(TakeOutParam(true, out var x8), x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d,a(Dummy(TakeOutParam(true, out var x9), x9)))
{
Dummy(x9);
using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
var y12 = 12;
}
//void Test13()
//{
// using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13)))
// let y13 = 12;
//}
void Test14()
{
using (var d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
AssertContainedInDeclaratorArguments(x10Decl);
VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_11()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope
// using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
AssertContainedInDeclaratorArguments(x2Decl);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_DeclaratorArguments_12()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2(Dummy(TakeOutParam(true, out var x4), x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_13()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Dummy(x4);
}
void Test6()
{
fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9)))
{
Dummy(x9);
fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11))))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13))))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_14()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* d,x1(
Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)],
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p(Dummy(TakeOutParam(true, out var x3) && x3)))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)],
p2(Dummy(TakeOutParam(true, out var x4) && x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_15()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
bool Test4 [x4 && TakeOutParam(4, out var x4)];
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
private static void VerifyModelNotSupported(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax));
Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var identifierText = decl.Identifier().ValueText;
Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any());
Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText));
Assert.Null(model.GetSymbolInfo(decl.Type).Symbol);
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null);
VerifyModelNotSupported(model, references);
}
private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart));
Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType());
}
}
[Fact]
public void Scope_DeclaratorArguments_16()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
fixed
bool Test4 [x4 && TakeOutParam(4, out var x4)];
fixed
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
fixed
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
fixed
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
fixed
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField,
(int)ErrorCode.ERR_NoImplicitConv
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 [x4 && TakeOutParam(4, out var x4)];
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (20,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 [Dummy(x7, 2)];
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25),
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_17()
{
var source =
@"
public class X
{
public static void Main()
{
}
const
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
const
bool Test4 [x4 && TakeOutParam(4, out var x4)];
const
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
const
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
const
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
const
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_18()
{
var source =
@"
public class X
{
public static void Main()
{
}
event
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
event
bool Test4 [x4 && TakeOutParam(4, out var x4)];
event
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
event
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
event
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
event
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.ERR_EventNotDelegate,
(int)ErrorCode.WRN_UnreferencedEvent
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_19()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool d[2], Test3 (out var x3);
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (8,28): error CS1003: Syntax error, '[' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28),
// (8,39): error CS1003: Syntax error, ']' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39),
// (8,33): error CS8185: A declaration is not allowed in this context.
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_20()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool Test3[out var x3];
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,22): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22),
// (8,30): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30),
// (8,21): error CS7092: A fixed buffer may only have one dimension.
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21),
// (8,26): error CS0103: The name 'var' does not exist in the current context
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
}
[Fact]
public void StaticType()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out StaticType x1);
}
static object Test1(out StaticType x)
{
throw new System.NotSupportedException();
}
static class StaticType {}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters
// static object Test1(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19),
// (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType'
// Test1(out StaticType x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19)
);
}
[Fact]
public void GlobalCode_Catch_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34),
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42),
// (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13),
// (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Catch_02()
{
var source =
@"
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Block_01()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
}
object x2;
{
H.TakeOutParam(2, out var x2);
H.Dummy(x2);
}
{
H.TakeOutParam(3, out var x3);
}
H.Dummy(x3);
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,8): warning CS0168: The variable 'x2' is declared but never used
// object x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8),
// (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31),
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
}
[Fact]
public void GlobalCode_Block_02()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
System.Console.WriteLine(x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_For_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
for ( // 2
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42),
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_For_02()
{
var source =
@"
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_Foreach_01()
{
var source =
@"using static Helpers;
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
static class Helpers
{
public static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
public static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Foreach_02()
{
var source =
@"
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0));
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) &&
TakeOutParam(o2, out var x5) &&
x5 > 0));
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0));
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0),
x7);
Dummy(x7, 2);
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out var x9) &&
x9 > 0), x9);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) &&
x11 > 0), x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutField(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutField(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutField(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7),
// (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7),
// (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79),
// (37,9): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9),
// (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13),
// (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void GlobalCode_Lambda_02()
{
var source =
@"
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
System.Console.WriteLine(l());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_03()
{
var source =
@"
System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Query_01()
{
var source =
@"
using System.Linq;
bool Dummy(params object[] x) {return true;}
var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutField(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutField(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutField(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutField(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutField(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutField(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutField(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutField(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutField(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutField(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutField(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutField(model, y10Decl, y10Ref[0]);
VerifyNotAnOutField(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutField(model, y11Decl, y11Ref[0]);
VerifyNotAnOutField(model, y11Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7),
// (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18),
// (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
}
[Fact]
public void GlobalCode_Query_02()
{
var source =
@"
using System.Linq;
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutField(model, yDecl, yRef);
}
[Fact]
public void GlobalCode_Using_01()
{
var source =
@"
System.IDisposable Dummy(params object[] x) {return null;}
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_Using_02()
{
var source =
@"
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void GlobalCode_ExpressionStatement_01()
{
string source =
@"
H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out int x2);
H.TakeOutParam(3, out int x3);
object x3;
H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
private static void AssertNoGlobalStatements(SyntaxTree tree)
{
Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>());
}
[Fact]
public void GlobalCode_ExpressionStatement_02()
{
string source =
@"
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out var x2);
H.TakeOutParam(3, out var x3);
object x3;
H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ExpressionStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_IfStatement_01()
{
string source =
@"
if (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out int x2)) {}
if (H.TakeOutParam(3, out int x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
if (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
int x6 = 6;
if (H.Dummy())
{
string x6 = ""6"";
H.Dummy(x6);
}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (30,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17),
// (30,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21),
// (30,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used
// int x6 = 6;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5),
// (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// string x6 = "6";
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12),
// (33,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_IfStatement_02()
{
string source =
@"
if (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out var x2)) {}
if (H.TakeOutParam(3, out var x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
if (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,29): error CS0841: Cannot use local variable 'x5' before it is declared
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29),
// (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
}
[Fact]
public void GlobalCode_IfStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_IfStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_YieldReturnStatement_01()
{
string source =
@"
yield return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out int x2);
yield return H.TakeOutParam(3, out int x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_YieldReturnStatement_02()
{
string source =
@"
yield return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out var x2);
yield return H.TakeOutParam(3, out var x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_01()
{
string source =
@"
return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out int x2);
return H.TakeOutParam(3, out int x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_02()
{
string source =
@"
return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out var x2);
return H.TakeOutParam(3, out var x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
Test();
return H.Dummy(H.TakeOutParam(1, out var x1), x1);
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool Dummy(object x, object y)
{
System.Console.WriteLine(y);
return true;
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_ThrowStatement_01()
{
string source =
@"
throw H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out int x2);
throw H.TakeOutParam(3, out int x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ThrowStatement_02()
{
string source =
@"
throw H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out var x2);
throw H.TakeOutParam(3, out var x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_01()
{
string source =
@"
switch (H.TakeOutParam(1, out int x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out int x2)) {default: break;}
switch (H.TakeOutParam(3, out int x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {default: break;}
switch (H.TakeOutParam(51, out int x5))
{
default:
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_02()
{
string source =
@"
switch (H.TakeOutParam(1, out var x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out var x2)) {default: break;}
switch (H.TakeOutParam(3, out var x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {default: break;}
switch (H.TakeOutParam(51, out var x5))
{
default:
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
switch (H.TakeOutParam(1, out var x1))
{
default:
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
break;
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_WhileStatement_01()
{
string source =
@"
while (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out int x2)) {}
while (H.TakeOutParam(3, out int x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
while (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out int x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_02()
{
string source =
@"
while (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out var x2)) {}
while (H.TakeOutParam(3, out var x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
while (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out var x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_03()
{
string source =
@"
while (H.TakeOutParam(1, out var x1))
{
System.Console.WriteLine(x1);
break;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_DoStatement_01()
{
string source =
@"
do {} while (H.TakeOutParam(1, out int x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out int x2));
do {} while (H.TakeOutParam(3, out int x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4)));
do
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out int x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out int x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out int x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_02()
{
string source =
@"
do {} while (H.TakeOutParam(1, out var x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out var x2));
do {} while (H.TakeOutParam(3, out var x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4)));
do
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out var x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out var x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out var x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_03()
{
string source =
@"
int f = 1;
do
{
}
while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3);
int Test(int x)
{
System.Console.WriteLine(x);
return x;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_LockStatement_01()
{
string source =
@"
lock (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out int x2)) {}
lock (H.TakeOutParam(3, out int x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
lock (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_02()
{
string source =
@"
lock (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out var x2)) {}
lock (H.TakeOutParam(3, out var x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
lock (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_LockStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_DeconstructionDeclarationStatement_01()
{
string source =
@"
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (16,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref[0]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_01()
{
string source =
@"
a: H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out int x2);
c: H.TakeOutParam(3, out int x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_02()
{
string source =
@"
a: H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out var x2);
c: H.TakeOutParam(3, out var x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_04()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out int x2);
e:
bool f = H.TakeOutParam(3, out int x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
i:
bool x5 = H.TakeOutParam(5, out int x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_05()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out var x2);
e:
bool f = H.TakeOutParam(3, out var x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
i:
bool x5 = H.TakeOutParam(5, out var x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void GlobalCode_LabeledStatement_06_Script()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_06_SimpleProgram()
{
string source =
@"
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(compilation, expectedOutput:
@"1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_07()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_08()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out var x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out var x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
H.TakeOutParam(6, out var x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_09()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var (d, e) = (H.TakeOutParam(1, out var x1), 1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_01()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out int x2);
bool f = H.TakeOutParam(3, out int x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 =
H.TakeOutParam(5, out int x5);
bool i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_02()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out var x2);
bool f = H.TakeOutParam(3, out var x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 =
H.TakeOutParam(5, out var x5);
bool i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static var b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_05()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_06()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_07()
{
string source =
@"
Test();
bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
bool Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return false;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_01()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out int x2);
bool f { get; } = H.TakeOutParam(3, out int x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 { get; } =
H.TakeOutParam(5, out int x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_02()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out var x2);
bool f { get; } = H.TakeOutParam(3, out var x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 { get; } =
H.TakeOutParam(5, out var x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
bool d { get; set; } = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static bool b { get; } = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_05()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_06()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_01()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out int x2);
event System.Action f = H.TakeOutParam(3, out int x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
event System.Action x5 =
H.TakeOutParam(5, out int x5);
event System.Action i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_02()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out var x2);
event System.Action f = H.TakeOutParam(3, out var x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
event System.Action x5 =
H.TakeOutParam(5, out var x5);
event System.Action i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
event System.Action d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static event System.Action b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_05()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_06()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_07()
{
string source =
@"
Test();
event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
System.Action Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_DeclaratorArguments_01()
{
string source =
@"
bool a, b(out var x1);
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_02()
{
string source =
@"
label:
bool a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1),
// (4,9): error CS0165: Use of unassigned local variable 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_03()
{
string source =
@"
event System.Action a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_04()
{
string source =
@"
fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static int TakeOutParam<T>(T y, out T x)
{
x = y;
return 3;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"),
parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to 'b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12),
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_RestrictedType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out System.ArgIterator x2);
class H
{
public static void TakeOutParam(out System.ArgIterator x)
{
x = default(System.ArgIterator);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// public static void TakeOutParam(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37),
// (5,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out System.ArgIterator x2);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20),
// (3,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_StaticType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out StaticType x2);
class H
{
public static void TakeOutParam(out StaticType x)
{
x = default(System.ArgIterator);
}
}
static class StaticType{}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (5,31): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out StaticType x2);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31),
// (9,24): error CS0721: 'StaticType': static types cannot be used as parameters
// public static void TakeOutParam(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24),
// (3,24): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_InferenceFailure_01()
{
string source =
@"
H.TakeOutParam(out var x1, x1);
class H
{
public static void TakeOutParam(out int x, long y)
{
x = 1;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.TakeOutParam(out var x1, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact]
public void GlobalCode_InferenceFailure_02()
{
string source =
@"
var a = b;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_03()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = a;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = a;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_04()
{
string source =
@"
var a = x1;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single());
Assert.True(a.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32)
);
}
[Fact]
public void GlobalCode_InferenceFailure_05()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = x1;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = H.TakeOutParam(out var x1, b);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single();
var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl);
Assert.True(b.Type.IsErrorType());
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
Assert.False(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
}
[Fact]
public void GlobalCode_InferenceFailure_06()
{
string source =
@"
H.TakeOutParam(out var x1);
class H
{
public static int TakeOutParam<T>(out T x)
{
x = default(T);
return 123;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24),
// (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")]
public void GlobalCode_InferenceFailure_07()
{
string source =
@"
H.M((var x1, int x2));
H.M(x1);
class H
{
public static void M(object a) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10),
// (2,6): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6),
// (2,14): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14),
// (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5),
// (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object'
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")]
public void InferenceFailure_01()
{
string source =
@"
class H
{
object M1() => M(M(1), x1);
static object M(object o1) => o1;
static void M(object o1, object o2) {}
}
";
var node0 = SyntaxFactory.ParseCompilationUnit(source);
var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
var decl = SyntaxFactory.DeclarationExpression(
type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")),
designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1")));
var node1 = node0.ReplaceNode(one, decl);
var tree = node1.SyntaxTree;
Assert.NotNull(tree);
var compilation = CreateCompilation(new[] { tree });
compilation.VerifyDiagnostics(
// (4,24): error CS8185: A declaration is not allowed in this context.
// object M1() => M(M(varx1), x1);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24)
);
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_AliasInfo_01()
{
string source =
@"
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void GlobalCode_AliasInfo_02()
{
string source =
@"
using var = System.Int32;
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_03()
{
string source =
@"
using a = System.Int32;
H.TakeOutParam(1, out a x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_04()
{
string source =
@"
H.TakeOutParam(1, out int x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_1()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out var x1):
System.Console.WriteLine(x1);
break;
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case !TakeOutParam(3, out var x1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_2()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out UndeclaredType x1):
System.Console.WriteLine(x1);
break;
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19),
// (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?)
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, false, references);
}
private static void VerifyModelForOutFieldDuplicate(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, true, references);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool duplicate,
params IdentifierNameSyntax[] references)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(SymbolKind.Field, symbol.Kind);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText);
var names = model.LookupNames(decl.SpanStart);
if (duplicate)
{
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, symbols.Single());
}
Assert.Contains(decl.Identifier().ValueText, names);
var local = (IFieldSymbol)symbol;
var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement &&
(declarator.ArgumentList?.Contains(decl)).GetValueOrDefault();
// We're not able to get type information at such location (out var argument in global code) at this point
// See https://github.com/dotnet/roslyn/issues/13569
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type);
foreach (var reference in references)
{
var referenceInfo = model.GetSymbolInfo(reference);
symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText);
if (duplicate)
{
Assert.Null(referenceInfo.Symbol);
Assert.Contains(symbol, referenceInfo.CandidateSymbols);
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, referenceInfo.Symbol);
Assert.Same(symbol, symbols.Single());
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
}
if (!inFieldDeclaratorArgumentlist)
{
var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent;
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
}
else
{
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (dataFlow.Succeeded)
{
Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
}
[Fact]
public void MethodTypeArgumentInference_01()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out int a);
TakeOutParam(out long b);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int64");
}
[Fact]
public void MethodTypeArgumentInference_02()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var a);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out var a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_03()
{
var source =
@"
public class X
{
public static void Main()
{
long a = 0;
TakeOutParam(out int b, a);
int c;
TakeOutParam(out c, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out int b, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9),
// (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out c, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_04()
{
var source =
@"
public class X
{
public static void Main()
{
byte a = 0;
int b = 0;
TakeOutParam(out int c, a);
TakeOutParam(out b, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int32");
}
[Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")]
public void OutVarDeclaredInReceiverUsedInArgument()
{
var source =
@"using System.Linq;
public class C
{
public string[] Goo2(out string x) { x = """"; return null; }
public string[] Goo3(bool b) { return null; }
public string[] Goo5(string u) { return null; }
public void Test()
{
var t1 = Goo2(out var x1).Concat(Goo5(x1));
var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First()));
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
}
[Fact]
public void OutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(out int _);
M(out var _);
M(out _);
}
static void M(out int x) { x = 1; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.Single();
var model = comp.Compilation.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetTypeInfo(discard1).Type);
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetTypeInfo(discard2).Type);
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard3));
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
comp.VerifyIL("C.Main()", @"
{
// Code size 22 (0x16)
.maxstack 1
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: call ""void C.M(out int)""
IL_0007: ldloca.s V_0
IL_0009: call ""void C.M(out int)""
IL_000e: ldloca.s V_0
IL_0010: call ""void C.M(out int)""
IL_0015: ret
}
");
}
[Fact]
public void NamedOutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(y: out string _, x: out int _);
M(y: out var _, x: out var _);
M(y: out _, x: out _);
}
static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
}
[Fact]
public void OutVarDiscardInCtor_01()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out int i1);
new C(out int _);
new C(out var _);
new C(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CCCC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("int", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
}
[Fact]
public void OutVarDiscardInCtor_02()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out long x1);
new C(out long _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19),
// (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long _);
Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19),
// (7,19): error CS0165: Use of unassigned local variable 'x1'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl);
var discard1 = GetDiscardDesignations(tree).Single();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("long _", declaration1.ToString());
Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("long", declaration1.Type.ToString());
Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
}
[Fact]
public void OutVarDiscardAliasInfo_01()
{
var source =
@"
using alias1 = System.Int32;
using var = System.Int32;
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString());
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString());
}
[Fact]
public void OutVarDiscardAliasInfo_02()
{
var source =
@"
enum alias1 : long {}
class var {}
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int'
// new C(out alias1 _);
Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19),
// (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int'
// new C(out var _);
Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString());
Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind);
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
}
[Fact]
public void OutVarDiscardInCtorInitializer()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C ""); }
static void Main()
{
new Derived2(out int i2);
new Derived3(out int i3);
new Derived4();
}
}
public class Derived2 : C
{
public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); }
}
public class Derived3 : C
{
public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); }
}
public class Derived4 : C
{
public Derived4(out int i) : base(out _) { i = 4; }
public Derived4() : this(out _) { System.Console.Write(""Derived4""); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4");
}
[Fact]
public void DiscardNotRecognizedInOtherScenarios()
{
var source =
@"
public class C
{
void M<T>()
{
_.ToString();
M(_);
_<T>.ToString();
(_<T>, _<T>) = (1, 2);
M<_>();
new C() { _ = 1 };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,9): error CS0103: The name '_' does not exist in the current context
// _.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9),
// (7,11): error CS0103: The name '_' does not exist in the current context
// M(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11),
// (8,9): error CS0103: The name '_' does not exist in the current context
// _<T>.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9),
// (9,10): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10),
// (9,16): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16),
// (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// M<_>();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11),
// (11,19): error CS0117: 'C' does not contain a definition for '_'
// new C() { _ = 1 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19)
);
}
[Fact]
public void TypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
System.Console.Write(t.GetType().ToString());
}
static void Main()
{
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "System.Int32");
}
[Fact]
public void UntypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
}
static void Main()
{
M(out var _);
M(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out var _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9),
// (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9)
);
}
[Fact]
public void PickOverloadWithTypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); }
static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); }
static void Main()
{
M(out object _);
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "object returning M. int returning M.");
}
[Fact]
public void CannotPickOverloadWithUntypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; }
static void M(out int x) { x = 2; }
static void Main()
{
M(out var _);
M(out _);
M(out byte _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out var _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9),
// (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9),
// (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object'
// M(out byte _);
Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15)
);
}
[Fact]
public void NoOverloadWithDiscard()
{
var source =
@"
public class A { }
public class B : A
{
static void M(A a)
{
a.M2(out A x);
a.M2(out A _);
}
}
public static class S
{
public static void M2(this A self, out B x) { x = null; }
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore });
comp.VerifyDiagnostics(
// (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A x);
Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18),
// (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A _);
Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18)
);
}
[Fact]
[WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")]
public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier()
{
var source =
@"
public class C
{
static void M(string x)
{
if(true)
&& int.TryParse(x, out int y)) id(iVal);
// Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single();
Assert.Equal("x", x.ToString());
Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString());
}
[Fact]
public void DuplicateDeclarationInSwitchBlock()
{
var text = @"
public class C
{
public static void Main(string[] args)
{
switch (args.Length)
{
case 0:
M(M(out var x1), x1);
M(M(out int x1), x1);
break;
case 1:
M(M(out int x1), x1);
break;
}
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}";
var comp = CreateCompilationWithMscorlib45(text);
comp.VerifyDiagnostics(
// (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29),
// (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29),
// (13,34): error CS0165: Use of unassigned local variable 'x1'
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x6Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x6Decl.Length);
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]);
}
[Fact]
public void DeclarationInLocalFunctionParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(int a, int b) => a+b == 0;
}
";
// the scope of an expression variable introduced in the default expression
// of a local function parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,75): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30),
// (6,61): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61),
// (7,75): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30),
// (7,61): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInAnonymousMethodParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
System.Action<bool, int> d1 = delegate (
bool b = M(M(out int z1), z1),
int s2 = z1)
{ var t = z1; };
System.Action<bool, int> d2 = delegate (
bool b = M(M(out var z2), z2),
int s2 = z2)
{ var t = z2; };
int x = z1 + z2;
d1 = d2 = null;
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}
";
// the scope of an expression variable introduced in the default expression
// of a lambda parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify(
// (9,55): error CS0103: The name 'z1' does not exist in the current context
// { var t = z1; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55),
// (13,55): error CS0103: The name 'z2' does not exist in the current context
// { var t = z2; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55),
// (15,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17),
// (15,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First();
Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString());
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void Scope_LocalFunction_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_05()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_LocalFunction_Attribute_06()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_InvalidArrayDimensions01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
int[Test1(out int x1), x1] _1;
int[Test1(out int x2), x2] x2;
}
static int Test1(out int x)
{
x = 1;
return 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12),
// (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27),
// (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12),
// (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13),
// (7,27): warning CS0168: The variable 'x1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27),
// (7,36): warning CS0168: The variable '_1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36),
// (8,27): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27),
// (8,36): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyNotAnOutLocal(model, x1Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref);
}
[Fact]
public void Scope_InvalidArrayDimensions_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using (int[] d = null)
{
Dummy(x1);
}
}
void Test2()
{
using (int[] d = null)
Dummy(x2);
}
void Test3()
{
var x3 = 11;
Dummy(x3);
using (int[] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 3; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16),
// file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19),
// file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// file.cs(14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16),
// file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19),
// file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51),
// file.cs(21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16),
// file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19),
// file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51),
// file.cs(30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using int[TakeOutParam(true, out var x1), x1] d = null;
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
using int[TakeOutParam(true, out var x2), x2] d = null;
Dummy(x2);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9),
// (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18),
// (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19),
// (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// (13,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15),
// (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9),
// (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18),
// (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19),
// (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46),
// (21,46): warning CS0168: The variable 'x2' is declared but never used
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyNotAnOutLocal(model, x2Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true);
}
[Fact]
public void Scope_InvalidArrayDimensions_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(object x) {return true;}
void Test1()
{
for (int[] a = null;;)
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
for (int[] a = null;;)
Dummy(x2);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 2; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17),
// file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18),
// file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49),
// file.cs(13,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19),
// file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53),
// file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17),
// file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45),
// file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18),
// file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49),
// file.cs(22,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19),
// file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
unsafe void Test1()
{
fixed (int[TakeOutParam(true, out var x1), x1] d = null)
{
Dummy(x1);
}
}
unsafe void Test2()
{
fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Dummy(x2);
}
unsafe void Test3()
{
var x3 = 11;
Dummy(x3);
fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test1()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17),
// (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19),
// (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52),
// (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56),
// (14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test2()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17),
// (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19),
// (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52),
// (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56),
// (21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test3()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17),
// (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19),
// (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52),
// (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56),
// (30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void DeclarationInNameof_00()
{
var text = @"
class C
{
public static void Main()
{
var x = nameof(M2(M1(out var x1), x1)).ToString();
}
static int M1(out int z) => z = 1;
static int M2(int a, int b) => 2;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,24): error CS8081: Expression does not have a name.
// var x = nameof(M2(M1(out var x1), x1)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "x1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(1, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
public void DeclarationInNameof_01()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(object a, int b) => b == 0;
}
";
// the scope of an expression variable introduced in the default expression
// of a local function parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,83): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83),
// (6,39): error CS8081: Expression does not have a name.
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30),
// (6,69): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69),
// (7,83): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83),
// (7,39): error CS8081: Expression does not have a name.
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30),
// (7,69): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02a()
{
var text = @"
[My(C.M(nameof(C.M(out int z1)), z1), z1)]
[My(C.M(nameof(C.M(out var z2)), z2), z2)]
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (2,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16),
// (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5),
// (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39),
// (3,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16),
// (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5),
// (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02b()
{
var text1 = @"
[assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
[assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
";
var text2 = @"
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 });
compilation.VerifyDiagnostics(
// (2,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26),
// (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15),
// (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49),
// (3,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26),
// (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15),
// (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_03()
{
var text = @"
class C
{
public static void Main(string[] args)
{
switch ((object)args.Length)
{
case !M(nameof(M(out int z1)), z1):
System.Console.WriteLine(z1);
break;
case !M(nameof(M(out var z2)), z2):
System.Console.WriteLine(z2);
break;
}
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (8,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28),
// (8,18): error CS0150: A constant value is expected
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18),
// (11,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28),
// (11,18): error CS0150: A constant value is expected
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18),
// (8,44): error CS0165: Use of unassigned local variable 'z1'
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44),
// (11,44): error CS0165: Use of unassigned local variable 'z2'
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_04()
{
var text = @"
class C
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
const bool c = (z1 + z2) == 0;
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (5,29): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29),
// (5,20): error CS0133: The expression being assigned to 'C.b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20),
// (6,21): error CS0103: The name 'z1' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21),
// (6,26): error CS0103: The name 'z2' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26),
// (4,29): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29),
// (4,20): error CS0133: The expression being assigned to 'C.a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_05()
{
var text = @"
class C
{
public static void Main(string[] args)
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
bool c = (z1 + z2) == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,33): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33),
// (6,24): error CS0133: The expression being assigned to 'a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24),
// (7,33): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33),
// (7,24): error CS0133: The expression being assigned to 'b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24),
// (6,49): error CS0165: Use of unassigned local variable 'z1'
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49),
// (7,49): error CS0165: Use of unassigned local variable 'z2'
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_06()
{
var text = @"
class C
{
public static void Main(string[] args)
{
string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
bool c = z1 == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27),
// (7,18): error CS0103: The name 'z1' does not exist in the current context
// bool c = z1 == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "z1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVar(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_01()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p =>
{
weakRef.TryGetTarget(out var x);
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_02()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_03()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
void Local1 (Action<T> onNext = p3 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_04()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_05()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y
select (Action<T>)( p =>
{
void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
)
)
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_06()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[p =>
{
weakRef.TryGetTarget(out var x);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_07()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_08()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
System.Type t3 = typeof(int[p3 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_09()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_10()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[from p in y
select (Action<T>)( p =>
{
System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
)
]
);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")]
public void GetEnclosingBinderInternalRecovery_11()
{
var text = @"
class Program
{
static void Main(string[] args)
{
foreach
other(some().F(a => TestOutVar(out var x) ? x : 1));
}
static void TestOutVar(out int a)
{
a = 0;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (6,16): error CS1003: Syntax error, '(' expected
// foreach
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16),
// (7,60): error CS1515: 'in' expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60),
// (7,60): error CS0230: Type and identifier are both required in a foreach statement
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60),
// (7,60): error CS1525: Invalid expression term ';'
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60),
// (7,60): error CS1026: ) expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var xDecl = GetOutVarDeclaration(tree, "x");
var xRef = GetReferences(tree, "x", 1);
VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates()
{
var source =
@"using System;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Func<int, bool> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (6,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Expression()
{
var source =
@"using System;
using System.Linq.Expressions;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Expression<Func<int, bool>> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (7,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Query()
{
var source =
@"using System.Linq;
class C
{
static void M()
{
var c = from x in new[] { 1, 2, 3 }
group x > 1 && F(out var y) && y == null
by x;
}
static bool F(out object o)
{
o = null;
return true;
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")]
public void SpeculativeSemanticModelWithOutDiscard()
{
var source =
@"class C
{
static void F()
{
C.G(out _);
}
static void G(out object o)
{
o = null;
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var identifierBefore = GetReferences(tree, "G").Single();
Assert.Equal(tree, identifierBefore.Location.SourceTree);
var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First();
var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);");
bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model);
Assert.True(success);
var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G");
Assert.Null(identifierAfter.Location.SourceTree);
var info = model.GetSymbolInfo(identifierAfter);
Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")]
[WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")]
public void GetForEachSymbolInfoWithOutVar()
{
var source =
@"using System.Collections.Generic;
public class C
{
void M()
{
foreach (var x in M2(out int i)) { }
}
IEnumerable<object> M2(out int j)
{
throw null;
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single();
var info = model.GetForEachStatementInfo(foreachStatement);
Assert.Equal("System.Object", info.ElementType.ToTestDisplayString());
Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()",
info.GetEnumeratorMethod.ToTestDisplayString());
}
[WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")]
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void DiscardAndArgList()
{
var text = @"
using System;
public class C
{
static void Main()
{
M(out _, __arglist(2, 3, true));
}
static void M(out int x, __arglist)
{
x = 0;
DumpArgs(new ArgIterator(__arglist));
}
static void DumpArgs(ArgIterator args)
{
while(args.GetRemainingCount() > 0)
{
TypedReference tr = args.GetNextArg();
object arg = TypedReference.ToObject(tr);
Console.Write(arg);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "23True");
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_01()
{
var text = @"
public class C
{
static void Main()
{
M(1, __arglist(out int y));
M(2, __arglist(out var z));
System.Console.WriteLine(z);
}
static void M(int x, __arglist)
{
x = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(1, __arglist(out int y));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28),
// (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32),
// (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_02()
{
var text = @"
public class C
{
static void Main()
{
__arglist(out int y);
__arglist(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23),
// (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9),
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27),
// (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23),
// (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_01()
{
var text = @"
public class C
{
static void M<T>() where T : new()
{
var x = new T(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z)", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)')
Children(1):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_02()
{
var text = @"
public class C
{
static void M<T>() where T : C, new()
{
var x = new T(out var z) {F1 = 1};
System.Console.WriteLine(z);
}
public int F1;
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z) {F1 = 1};
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z) {F1 = 1}", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}')
Children(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1')
Left:
IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
");
}
[Fact]
public void EventInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
static System.Func<bool> GetDelegate(bool value) => () => value;
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConstructorBodyOperation()
{
var text = @"
public class C
{
C() : this(out var x)
{ M(out var y); }
=> M(out var z);
C (out int x){x=1;}
void M (out int x){x=1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(out var x)", initializerSyntax.ToString());
compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree:
@"
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation initializerOperation = model.GetOperation(initializerSyntax);
Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind);
Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent);
Assert.Null(blockBodyOperation.Parent.Parent);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent);
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);')
Locals: Local_1: System.Int32 x
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Expression:
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void MethodBodyOperation()
{
var text = @"
public class C
{
int P
{
get {return M(out var x);} => M(out var y);
} => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax);
Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind);
Assert.Null(expressionBodyOperation.Parent.Parent);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent);
var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1);
Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString());
Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single();
Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);')
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyExpressionBodyOperation()
{
var text = @"
public class C
{
int P => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", node3.ToString());
compilation.VerifyOperationTree(node3, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Null(model.GetOperation(node3).Parent);
}
[Fact]
public void OutVarInConstructorUsedInObjectInitializer()
{
var source =
@"
public class C
{
public int Number { get; set; }
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { Number = i };
System.Console.WriteLine(c.Number);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
public void OutVarInConstructorUsedInCollectionInitializer()
{
var source =
@"
public class C : System.Collections.Generic.List<int>
{
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { i, i, i };
System.Console.WriteLine(c[0]);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
[WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")]
public void Issue49997()
{
var text = @"
public class Cls
{
public static void Main()
{
if ()
.Test1().Test2(out var x1).Test3();
}
}
static class Ext
{
public static void Test3(this Cls x) {}
}
";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last();
Assert.True(model.GetSymbolInfo(node).IsEmpty);
}
}
internal static class OutVarTestsExtensions
{
internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self)
{
return (SingleVariableDesignationSyntax)self.Designation;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using static Roslyn.Test.Utilities.TestMetadata;
using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.OutVar)]
public class OutVarTests : CompilingTestBase
{
[Fact]
public void OldVersion()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")]
[WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")]
public void DiagnosticsDifferenceBetweenLanguageVersions_01()
{
var text = @"
public class Cls
{
public static void Test1()
{
Test(out int x1);
}
public static void Test2()
{
var x = new Cls(out int x2);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test(out int x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22),
// (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33),
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (var x1, var x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, long x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,28): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, (long x2, byte x3)));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,29): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29),
// (6,38): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38),
// (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,29): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29),
// (6,38): error CS0165: Use of unassigned local variable 'x3'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_05()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2, x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_06()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
Test1(out var (x1));
System.Console.WriteLine(F1);
}
static ref int var(object x)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_07()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, x2: x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2: x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_08()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (ref x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(ref object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (ref x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_09()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, (x2)));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_10()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var ((x1), x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var ((x1), x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_12()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out M1 (x1, x2));
System.Console.WriteLine(F1);
}
static ref int M1(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_13()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(ref var (x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(ref int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(ref var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_14()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(var (x1, x2));
System.Console.WriteLine(F1);
}
static int var(object x1, object x2)
{
F1 = 123;
return 124;
}
static object Test1(int x)
{
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"124
123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_15()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out M1 (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int M1(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_16()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (a: x2, b: x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (a: x2, b: x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name)
{
return GetReferences(tree, name).Single();
}
private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count)
{
var nameRef = GetReferences(tree, name).ToArray();
Assert.Equal(count, nameRef.Length);
return nameRef;
}
internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name);
}
private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == name);
}
private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name)
{
return GetDeclarations(tree, name).Single();
}
internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name)
{
return GetOutVarDeclarations(tree, name).Single();
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name);
}
private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>();
}
private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken);
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration());
}
[Fact]
public void Simple_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
int x2;
Test3(out x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references);
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references);
}
private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references);
}
internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(
SemanticModel model,
DeclarationExpressionSyntax decl,
IdentifierNameSyntax reference)
{
VerifyModelForOutVar(
model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false,
verifyDataFlow: true, references: reference);
}
private static void VerifyModelForOutVar(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool isDelegateCreation,
bool isExecutableCode,
bool isShadowed,
bool verifyDataFlow = true,
LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax);
Assert.NotNull(symbol);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.False(((ILocalSymbol)symbol).IsFixed);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single();
if (isShadowed)
{
Assert.NotEqual(symbol, other);
}
else
{
Assert.Same(symbol, other);
}
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type);
foreach (var reference in references)
{
Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
if (verifyDataFlow)
{
VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol);
}
}
private static void AssertInfoForDeclarationExpressionSyntax(
SemanticModel model,
DeclarationExpressionSyntax decl,
ISymbol expectedSymbol = null,
ITypeSymbol expectedType = null
)
{
var symbolInfo = model.GetSymbolInfo(decl);
Assert.Equal(expectedSymbol, symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl));
var typeInfo = model.GetTypeInfo(decl);
Assert.Equal(expectedType, typeInfo.Type);
// skip cases where operation is not supported
AssertTypeFromOperation(model, expectedType, decl);
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.Equal(expectedType, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl));
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.True(model.GetConversion(decl).IsIdentity);
var typeSyntax = decl.Type;
Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));
ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType();
if (expected?.IsErrorType() != false)
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol);
}
typeInfo = model.GetTypeInfo(typeSyntax);
Assert.Equal(expected, typeInfo.Type);
Assert.Equal(expected, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax));
Assert.True(model.GetConversion(typeSyntax).IsIdentity);
var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false);
Assert.False(conversion.Exists);
Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Null(model.GetDeclaredSymbol(decl));
}
private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl)
{
// see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail
// unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode.
// what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from
// error recovery mode
var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault();
if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true)
{
// invalid syntax case where operation is not supported
return;
}
Assert.Equal(expectedType, model.GetOperation(decl)?.Type);
}
private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol)
{
var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax;
if (dataFlowParent == null)
{
if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax))
{
Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent);
}
return;
}
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
return;
}
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (isExecutableCode)
{
Assert.True(dataFlow.Succeeded);
Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
if (!isDelegateCreation)
{
Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
var flowsIn = FlowsIn(dataFlowParent, decl, references);
Assert.Equal(flowsIn,
dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(flowsIn,
dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(FlowsOut(dataFlowParent, decl, references),
dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(ReadOutside(dataFlowParent, references),
dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(WrittenOutside(dataFlowParent, references),
dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type);
}
private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
Assert.NotEqual(SymbolKind.Field, symbol.Kind);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
if (symbol.Kind == SymbolKind.Local)
{
var local = symbol.GetSymbol<SourceLocalSymbol>();
var parent = local.IdentifierToken.Parent;
Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration()));
if (parent.Kind() == SyntaxKind.VariableDeclarator)
{
var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent;
switch (parent1.Kind())
{
case SyntaxKind.FixedStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.UsingStatement:
break;
default:
Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind());
break;
}
}
}
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl)
{
return (SingleVariableDesignationSyntax)decl.Designation;
}
private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart)
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool IsRead(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left != reference)
{
return true;
}
break;
default:
return true;
}
return false;
}
private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
ForStatementSyntax forStatement;
if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null &&
forStatement.Incrementors.Span.Contains(decl.Position) &&
forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null))
{
return false;
}
var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault();
var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax);
MethodDeclarationSyntax methodDeclParent;
if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" &&
((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null ||
methodDeclParent.Body.Statements.First() != containingReturnOrThrow))
{
return false;
}
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span) &&
(containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) &&
(reference.SpanStart > decl.SpanStart ||
(containingReturnOrThrow == null &&
reference.Ancestors().OfType<DoStatementSyntax>().Join(
decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any())))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsWrite(reference))
{
return true;
}
}
}
return false;
}
private static bool IsWrite(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left == reference)
{
return true;
}
break;
case SyntaxKind.PreIncrementExpression:
case SyntaxKind.PostIncrementExpression:
case SyntaxKind.PreDecrementExpression:
case SyntaxKind.PostDecrementExpression:
return true;
default:
return false;
}
return false;
}
[Fact]
public void Simple_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Int32 x1), x1);
int x2 = 0;
Test3(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out (int, int) x1), x1);
}
static object Test1(out (int, int) x)
{
x = (123, 124);
return null;
}
static void Test2(object x, (int, int) y)
{
System.Console.WriteLine(y);
}
}
namespace System
{
// struct with two values
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}
" + TestResources.NetFX.ValueTuple.tupleattributes_cs;
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1);
}
static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = new System.Collections.Generic.List<System.Int32>();
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, out x1), x1);
}
static object Test1(out int x, out int y)
{
x = 123;
y = 124;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, x1 = 124), x1);
}
static object Test1(out int x, int y)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1, x1 = 124);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y, int z)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), ref x1);
int x2 = 0;
Test3(ref x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, ref int y)
{
System.Console.WriteLine(y);
}
static void Test3(ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), out x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_10()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out dynamic x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int[] x1), x1);
}
static object Test1(out int[] x)
{
x = new [] {123};
return null;
}
static void Test2(object x, int[] y)
{
System.Console.WriteLine(y[0]);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
Test1(out int x1);
Test2(Test1(out int x2),
out int x2);
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS0128: A local variable named 'x1' is already defined in this scope
// Test1(out int x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23),
// (9,29): error CS0128: A local variable named 'x2' is already defined in this scope
// out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13)
);
}
[Fact]
public void Scope_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, object x)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15)
);
}
[Fact]
public void Scope_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out int x1);
System.Console.WriteLine(x1);
}
static object Test1(out int x)
{
x = 1;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out var x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void AttributeArgument_01()
{
var source =
@"
public class X
{
[Test(out var x3)]
[Test(out int x4)]
[Test(p: out var x5)]
[Test(p: out int x6)]
public static void Main()
{
}
}
class Test : System.Attribute
{
public Test(out int p) { p = 100; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (4,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11),
// (4,19): error CS1003: Syntax error, ',' expected
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19),
// (5,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11),
// (5,15): error CS1525: Invalid expression term 'int'
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15),
// (5,19): error CS1003: Syntax error, ',' expected
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19),
// (6,14): error CS1525: Invalid expression term 'out'
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14),
// (6,14): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18),
// (6,22): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22),
// (7,14): error CS1525: Invalid expression term 'out'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14),
// (7,14): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14),
// (7,18): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22),
// (4,15): error CS0103: The name 'var' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15),
// (4,19): error CS0103: The name 'x3' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19),
// (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6),
// (5,19): error CS0103: The name 'x4' does not exist in the current context
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19),
// (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6),
// (6,18): error CS0103: The name 'var' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18),
// (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18),
// (6,22): error CS0103: The name 'x5' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22),
// (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6),
// (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18),
// (7,22): error CS0103: The name 'x6' does not exist in the current context
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22),
// (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6)
);
var tree = compilation.SyntaxTrees.Single();
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
Assert.False(GetOutVarDeclarations(tree, "x4").Any());
Assert.False(GetOutVarDeclarations(tree, "x5").Any());
Assert.False(GetOutVarDeclarations(tree, "x6").Any());
}
[Fact]
public void Scope_Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Scope_Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out int x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
int x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out int x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out int x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out int x7) && x7 > 0)
{
int x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out int x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out int x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out int x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out int x10))
{
int y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out int x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out int x14),
TakeOutParam(out int x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out int x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out int x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out int x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out int x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out int x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Catch_01_ExplicitType()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_03()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Catch_04()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Scope_ConstructorInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
X(byte x)
: this(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: this(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: this(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: this(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: this(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: this(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
X(params object[] x) {}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : this(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : this(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_02()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x)
: base(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: base(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: base(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: base(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: base(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: base(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : base(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : base(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_03()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D
{
public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_04()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D : C
{
public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_05()
{
var source =
@"using System;
class D
{
public D(int o) : this(SpeculateHere)
{
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_06()
{
var source =
@"using System;
class D : C
{
public D(int o) : base(SpeculateHere)
{
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var initializerOperation = model.GetOperation(initializer);
Assert.Null(initializerOperation.Parent.Parent.Parent);
VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @"
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)')
Children(1):
IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5')
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5')
Left:
IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o')
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5')
Left:
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
public void Scope_ConstructorInitializers_07()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x3)
: base(TakeOutParam(3, out var x3))
{}
X(sbyte x)
: base(TakeOutParam(4, out var x4))
{
int x4 = 1;
System.Console.WriteLine(x4);
}
X(ushort x)
: base(TakeOutParam(51, out var x5))
=> Dummy(TakeOutParam(52, out var x5), x5);
X(short x)
: base(out int x6, x6)
{}
X(uint x)
: base(out var x7, x7)
{}
X(int x)
: base(TakeOutParam(out int x8, x8))
{}
X(ulong x)
: base(TakeOutParam(out var x9, x9))
{}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
public Y(out int x, int y) { x = y; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : base(TakeOutParam(3, out var x3))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40),
// (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x4 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13),
// (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// => Dummy(TakeOutParam(52, out var x5), x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39),
// (24,28): error CS0165: Use of unassigned local variable 'x6'
// : base(out int x6, x6)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28),
// (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list.
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28),
// (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20),
// (32,41): error CS0165: Use of unassigned local variable 'x8'
// : base(TakeOutParam(out int x8, x8))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41),
// (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list.
// : base(TakeOutParam(out var x9, x9))
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").Single();
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref);
}
[Fact]
public void Scope_Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
do
{
Dummy(x1);
}
while (TakeOutParam(true, out var x1) && x1);
}
void Test2()
{
do
Dummy(x2);
while (TakeOutParam(true, out var x2) && x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
do
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4);
}
void Test6()
{
do
Dummy(x6);
while (x6 && TakeOutParam(true, out var x6));
}
void Test7()
{
do
{
var x7 = 12;
Dummy(x7);
}
while (TakeOutParam(true, out var x7) && x7);
}
void Test8()
{
do
Dummy(x8);
while (TakeOutParam(true, out var x8) && x8);
System.Console.WriteLine(x8);
}
void Test9()
{
do
{
Dummy(x9);
do
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9); // 2
}
while (TakeOutParam(true, out var x9) && x9);
}
void Test10()
{
do
{
var y10 = 12;
Dummy(y10);
}
while (TakeOutParam(y10, out var x10));
}
//void Test11()
//{
// do
// {
// let y11 = 12;
// Dummy(y11);
// }
// while (TakeOutParam(y11, out var x11));
//}
void Test12()
{
do
var y12 = 12;
while (TakeOutParam(y12, out var x12));
}
//void Test13()
//{
// do
// let y13 = 12;
// while (TakeOutParam(y13, out var x13));
//}
void Test14()
{
do
{
Dummy(x14);
}
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13),
// (14,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19),
// (22,19): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19),
// (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43),
// (32,19): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy(x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19),
// (40,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16),
// (39,19): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19),
// (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17),
// (56,19): error CS0841: Cannot use local variable 'x8' before it is declared
// Dummy(x8);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19),
// (59,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34),
// (66,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19),
// (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9); // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47),
// (68,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23),
// (81,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29),
// (98,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29),
// (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17),
// (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46),
// (112,19): error CS0841: Cannot use local variable 'x14' before it is declared
// Dummy(x14);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[1]);
VerifyNotAnOutLocal(model, x7Ref[0]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[1]);
VerifyNotAnOutLocal(model, y10Ref[0]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
do
{
}
while (TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@"
do {} while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f;
do
{
f = false;
}
while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
do
;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false);
if (f)
{
do
;
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Do_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1)));
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3
--
1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0;
bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0;
void Test72() => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test11(object x11) => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,29): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29),
// (13,67): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67),
// (19,28): error CS0103: The name 'x7' does not exist in the current context
// void Test72() => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool Test11(object x11) => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")]
public void Scope_ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test3()
{
bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0;
f(null);
}
void Test4()
{
bool f (object o) => x4 && TakeOutParam(o, out int x4);
f(null);
}
void Test5()
{
bool f (object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
f(null, null);
}
void Test6()
{
bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
f1(null);
f2(null);
}
void Test7()
{
Dummy(x7, 1);
bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0;
Dummy(x7, 2);
f(null);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
bool f (object o) => TakeOutParam(o, out int x11) &&
x11 > 0;
f(null);
}
void Test12()
{
bool f (object o) => TakeOutParam(o, out int x12) &&
x12 > 0;
var x12 = 11;
Dummy(x12);
f(null);
}
System.Action Test13()
{
return () =>
{
bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0;
f(null);
};
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15),
// (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54),
// (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
// Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").Single();
VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref);
}
[Fact]
public void ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out int x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedLocalFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out var x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void Scope_ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 => TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 => x4 && TakeOutParam(4, out int x4);
bool Test5 => TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 => TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool this[object x11] => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,19): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 => x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19),
// (13,44): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44),
// (19,26): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool this[object x11] => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void ExpressionBodiedProperties_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void Scope_ExpressionStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
Dummy(TakeOutParam(true, out var x1), x1);
{
Dummy(TakeOutParam(true, out var x1), x1);
}
Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ExpressionStatement_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
Test2(Test1(out int x1), x1);
if (test)
{
Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_ExpressionStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ExpressionStatement_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Scope_FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 = x4 && TakeOutParam(4, out int x4);
bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,57): error CS0103: The name 'x8' does not exist in the current context
// bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57),
// (23,19): error CS0103: The name 'x9' does not exist in the current context
// bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReference(tree, "x8");
VerifyModelForOutVar(model, x8Decl);
VerifyNotInScope(model, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReference(tree, "x9");
VerifyNotInScope(model, x9Ref);
VerifyModelForOutVar(model, x9Decl);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_FieldInitializers_02()
{
var source =
@"using static Test;
public enum X
{
Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0,
Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Test72 = x7,
}
class Test
{
public static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,13): error CS0841: Cannot use local variable 'x4' before it is declared
// Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13),
// (9,38): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38),
// (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant
// Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13),
// (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14),
// (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70),
// (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant
// Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14),
// (15,14): error CS0103: The name 'x7' does not exist in the current context
// Test72 = x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14),
// (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant
// Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0')
Locals: Local_1: System.Int32 x3
IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0')
Condition:
IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenTrue:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
WhenFalse:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
const bool Test4 = x4 && TakeOutParam(4, out int x4);
const bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
const bool Test72 = x7 > 2;
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant
// const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24),
// (10,24): error CS0841: Cannot use local variable 'x4' before it is declared
// const bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24),
// (13,49): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49),
// (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant
// const bool Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("X.Test5").WithLocation(12, 24),
// (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25),
// (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73),
// (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant
// const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// const bool Test72 = x7 > 2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_FieldInitializers_04()
{
var source =
@"
class X : Y
{
public static void Main()
{
}
bool Test3 = TakeOutParam(out int x3, x3);
bool Test4 = TakeOutParam(out var x4, x4);
bool Test5 = TakeOutParam(out int x5, 5);
X()
: this(x5)
{
System.Console.WriteLine(x5);
}
X(object x)
: base(x5)
=> System.Console.WriteLine(x5);
static bool Test6 = TakeOutParam(out int x6, 6);
static X()
{
System.Console.WriteLine(x6);
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
class Y
{
public Y(object y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,43): error CS0165: Use of unassigned local variable 'x3'
// bool Test3 = TakeOutParam(out int x3, x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43),
// (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list.
// bool Test4 = TakeOutParam(out var x4, x4);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43),
// (15,12): error CS0103: The name 'x5' does not exist in the current context
// : this(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12),
// (17,34): error CS0103: The name 'x5' does not exist in the current context
// System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34),
// (21,12): error CS0103: The name 'x5' does not exist in the current context
// : base(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12),
// (22,33): error CS0103: The name 'x5' does not exist in the current context
// => System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33),
// (27,34): error CS0103: The name 'x6' does not exist in the current context
// System.Console.WriteLine(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(4, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
VerifyNotInScope(model, x5Ref[3]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")]
public void FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1);
static bool Dummy(System.Func<int> x)
{
System.Console.WriteLine(x());
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void FieldInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void FieldInitializers_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,54): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void FieldInitializers_06()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void Scope_Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p = Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p = Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* x1 =
Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2),
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p = Dummy(TakeOutParam(true, out var x3) && x3))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4),
p2 = Dummy(TakeOutParam(true, out var x4) && x4))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (14,66): error CS0165: Use of unassigned local variable 'x1'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2 = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Scope_For_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;
Dummy(TakeOutParam(true, out var x1) && x1)
;)
{
Dummy(x1);
}
}
void Test2()
{
for (;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;
Dummy(TakeOutParam(true, out var x4) && x4)
;)
Dummy(x4);
}
void Test6()
{
for (;
Dummy(x6 && TakeOutParam(true, out var x6))
;)
Dummy(x6);
}
void Test7()
{
for (;
Dummy(TakeOutParam(true, out var x7) && x7)
;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;
Dummy(TakeOutParam(true, out var x8) && x8)
;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;
Dummy(TakeOutParam(true, out var x9) && x9)
;)
{
Dummy(x9);
for (;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;)
Dummy(x9);
}
}
void Test10()
{
for (;
Dummy(TakeOutParam(y10, out var x10))
;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;
// Dummy(TakeOutParam(y11, out var x11))
// ;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;
Dummy(TakeOutParam(y12, out var x12))
;)
var y12 = 12;
}
//void Test13()
//{
// for (;
// Dummy(TakeOutParam(y13, out var x13))
// ;)
// let y13 = 12;
//}
void Test14()
{
for (;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(TakeOutParam(true, out var x1) && x1)
)
{
Dummy(x1);
}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2)
)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;;
Dummy(TakeOutParam(true, out var x4) && x4)
)
Dummy(x4);
}
void Test6()
{
for (;;
Dummy(x6 && TakeOutParam(true, out var x6))
)
Dummy(x6);
}
void Test7()
{
for (;;
Dummy(TakeOutParam(true, out var x7) && x7)
)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;;
Dummy(TakeOutParam(true, out var x8) && x8)
)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;;
Dummy(TakeOutParam(true, out var x9) && x9)
)
{
Dummy(x9);
for (;;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
)
Dummy(x9);
}
}
void Test10()
{
for (;;
Dummy(TakeOutParam(y10, out var x10))
)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;;
// Dummy(TakeOutParam(y11, out var x11))
// )
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;;
Dummy(TakeOutParam(y12, out var x12))
)
var y12 = 12;
}
//void Test13()
//{
// for (;;
// Dummy(TakeOutParam(y13, out var x13))
// )
// let y13 = 12;
//}
void Test14()
{
for (;;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (16,19): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19),
// (25,19): error CS0103: The name 'x2' does not exist in the current context
// Dummy(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (44,19): error CS0103: The name 'x6' does not exist in the current context
// Dummy(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19),
// (63,19): error CS0103: The name 'x8' does not exist in the current context
// Dummy(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (74,19): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19),
// (78,23): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23),
// (71,14): warning CS0162: Unreachable code detected
// Dummy(TakeOutParam(true, out var x9) && x9)
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44),
// (128,19): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref[0]);
VerifyNotInScope(model, x2Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref[0]);
VerifyNotInScope(model, x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0]);
VerifyNotInScope(model, x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyNotInScope(model, x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyNotInScope(model, x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
VerifyNotInScope(model, x14Ref[1]);
}
[Fact]
public void Scope_For_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (var b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (var b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (var b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (var b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (var b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (var b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (var b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (var b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (var b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (var b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (var b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (var b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (bool b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (bool b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (bool b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (bool b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (bool b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (bool b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var x1 =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{}
}
void Test2()
{
for (var x2 = true;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
{}
}
void Test3()
{
for (var x3 = true;;
Dummy(TakeOutParam(true, out var x3) && x3)
)
{}
}
void Test4()
{
for (bool x4 =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
{}
}
void Test5()
{
for (bool x5 = true;
Dummy(TakeOutParam(true, out var x5) && x5)
;)
{}
}
void Test6()
{
for (bool x6 = true;;
Dummy(TakeOutParam(true, out var x6) && x6)
)
{}
}
void Test7()
{
for (bool x7 = true, b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{}
}
void Test8()
{
for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8),
b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2 = Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
void Test10()
{
for (var b = x10;
Dummy(TakeOutParam(true, out var x10) && x10) &&
Dummy(TakeOutParam(true, out var x10) && x10);
Dummy(TakeOutParam(true, out var x10) && x10))
{}
}
void Test11()
{
for (bool b = x11;
Dummy(TakeOutParam(true, out var x11) && x11) &&
Dummy(TakeOutParam(true, out var x11) && x11);
Dummy(TakeOutParam(true, out var x11) && x11))
{}
}
void Test12()
{
for (Dummy(x12);
Dummy(x12) &&
Dummy(TakeOutParam(true, out var x12) && x12);
Dummy(TakeOutParam(true, out var x12) && x12))
{}
}
void Test13()
{
for (var b = x13;
Dummy(x13);
Dummy(TakeOutParam(true, out var x13) && x13),
Dummy(TakeOutParam(true, out var x13) && x13))
{}
}
void Test14()
{
for (bool b = x14;
Dummy(x14);
Dummy(TakeOutParam(true, out var x14) && x14),
Dummy(TakeOutParam(true, out var x14) && x14))
{}
}
void Test15()
{
for (Dummy(x15);
Dummy(x15);
Dummy(x15),
Dummy(TakeOutParam(true, out var x15) && x15))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47),
// (13,54): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54),
// (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x2) && x2)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47),
// (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used
// for (var x2 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3) && x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used
// for (var x3 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18),
// (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47),
// (37,54): error CS0165: Use of unassigned local variable 'x4'
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54),
// (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x5) && x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47),
// (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used
// for (bool x5 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19),
// (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x6) && x6)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47),
// (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used
// for (bool x6 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19),
// (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47),
// (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52),
// (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47),
// (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47),
// (77,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23),
// (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47),
// (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47),
// (86,22): error CS0103: The name 'x10' does not exist in the current context
// for (var b = x10;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22),
// (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope
// Dummy(TakeOutParam(true, out var x10) && x10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47),
// (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x10) && x10))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47),
// (95,23): error CS0103: The name 'x11' does not exist in the current context
// for (bool b = x11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23),
// (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope
// Dummy(TakeOutParam(true, out var x11) && x11);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47),
// (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x11) && x11))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47),
// (104,20): error CS0103: The name 'x12' does not exist in the current context
// for (Dummy(x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20),
// (105,20): error CS0841: Cannot use local variable 'x12' before it is declared
// Dummy(x12) &&
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20),
// (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x12) && x12))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47),
// (113,22): error CS0103: The name 'x13' does not exist in the current context
// for (var b = x13;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22),
// (114,20): error CS0103: The name 'x13' does not exist in the current context
// Dummy(x13);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20),
// (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope
// Dummy(TakeOutParam(true, out var x13) && x13))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47),
// (122,23): error CS0103: The name 'x14' does not exist in the current context
// for (bool b = x14;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23),
// (123,20): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20),
// (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope
// Dummy(TakeOutParam(true, out var x14) && x14))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47),
// (131,20): error CS0103: The name 'x15' does not exist in the current context
// for (Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20),
// (132,20): error CS0103: The name 'x15' does not exist in the current context
// Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20),
// (133,20): error CS0841: Cannot use local variable 'x15' before it is declared
// Dummy(x15),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(3, x10Decl.Length);
Assert.Equal(4, x10Ref.Length);
VerifyNotInScope(model, x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]);
VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]);
var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Decl.Length);
Assert.Equal(4, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]);
VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]);
var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Decl.Length);
Assert.Equal(4, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]);
VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(4, x13Ref.Length);
VerifyNotInScope(model, x13Ref[0]);
VerifyNotInScope(model, x13Ref[1]);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyNotInScope(model, x14Ref[0]);
VerifyNotInScope(model, x14Ref[1]);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(4, x15Ref.Length);
VerifyNotInScope(model, x15Ref[0]);
VerifyNotInScope(model, x15Ref[1]);
VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]);
}
[Fact]
public void Scope_For_07()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(x1),
Dummy(TakeOutParam(true, out var x1) && x1))
{}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2),
Dummy(TakeOutParam(true, out var x2) && x2))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,20): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20),
// (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2) && x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
}
[Fact]
public void For_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_03()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_04()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_05()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 10
3 20
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(5, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_06()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)))
{
x0++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"20
30
--
20
30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_07()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
--
10
20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
void Test1()
{
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
void Test15()
{
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60),
// (35,33): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65),
// (68,46): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46),
// (86,46): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,57): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57),
// (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_If_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (TakeOutParam(true, out var x1))
{
Dummy(x1);
}
else
{
System.Console.WriteLine(x1);
}
}
void Test2()
{
if (TakeOutParam(true, out var x2))
Dummy(x2);
else
System.Console.WriteLine(x2);
}
void Test3()
{
if (TakeOutParam(true, out var x3))
Dummy(x3);
else
{
var x3 = 12;
System.Console.WriteLine(x3);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
if (TakeOutParam(true, out var x4))
Dummy(x4);
}
void Test5(int x5)
{
if (TakeOutParam(true, out var x5))
Dummy(x5);
}
void Test6()
{
if (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
if (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
if (TakeOutParam(true, out var x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
if (TakeOutParam(true, out var x9))
{
Dummy(x9);
if (TakeOutParam(true, out var x9)) // 2
Dummy(x9);
}
}
void Test10()
{
if (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
void Test12()
{
if (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// if (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13),
// (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x3 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17),
// (46,40): error CS0128: A local variable named 'x4' is already defined in this scope
// if (TakeOutParam(true, out var x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40),
// (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x5))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40),
// (58,13): error CS0841: Cannot use local variable 'x6' before it is declared
// if (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13),
// (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17),
// (83,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19),
// (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44),
// (91,26): error CS0103: The name 'y10' does not exist in the current context
// if (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26),
// (100,26): error CS0103: The name 'y12' does not exist in the current context
// if (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26),
// (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
}
[Fact]
public void Scope_If_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
if (TakeOutParam(true, out var x1))
{
}
else
{
}
x1++;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_If_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@"
if (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void If_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
Test(2);
}
public static void Test(int val)
{
if (Dummy(val == 1, TakeOutParam(val, out var x1), x1))
{
System.Console.WriteLine(""true"");
System.Console.WriteLine(x1);
}
else
{
System.Console.WriteLine(""false"");
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
true
1
1
2
false
2
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void If_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
;
if (f)
{
if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
System.Action<object> Test1()
{
return (o) => let x1 = o;
}
System.Action<object> Test2()
{
return (o) => let var x2 = o;
}
void Test3()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0));
}
void Test4()
{
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0));
}
void Test6()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0));
}
void Test7()
{
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0),
x7);
Dummy(x7, 2);
}
void Test8()
{
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8));
}
void Test9()
{
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
x9 > 0), x9);
}
void Test10()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
x11 > 0), x11);
}
void Test12()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73),
// (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73),
// (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73),
// (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
[Fact]
public void Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
return l();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
var d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// var d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// var d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
object d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
object d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
object d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
object d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,53): error CS0128: A local variable named 'x4' is already defined in this scope
// object d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53),
// (24,26): error CS0841: Cannot use local variable 'x6' before it is declared
// object d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26),
// (36,50): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var x1 =
Dummy(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
object x2 =
Dummy(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
public void Scope_LocalDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y1 = Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
public void Scope_LocalDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d =TakeOutParam(true, out var x1) && x1 != null;
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
public void LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2);
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (d, dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var (d, dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
var (d, dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var (d, dd, ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,51): error CS0128: A local variable named 'x4' is already defined in this scope
// var (d, dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51),
// (24,24): error CS0841: Cannot use local variable 'x6' before it is declared
// var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
(object d, object dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
(object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
(object d, object dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
(object d, object dd, object ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,61): error CS0128: A local variable named 'x4' is already defined in this scope
// (object d, object dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61),
// (24,34): error CS0841: Cannot use local variable 'x6' before it is declared
// (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (x1, dd) =
(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
(object x2, object dd) =
(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Dummy(x1));
Dummy(x1);
}
void Test2()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2),
Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3),
Dummy(x3));
}
void Test4()
{
(object d1, object d2) = (Dummy(x4),
Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,67): error CS0128: A local variable named 'x1' is already defined in this scope
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67),
// (12,72): error CS0165: Use of unassigned local variable 'x1'
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,41): error CS0841: Cannot use local variable 'x4' before it is declared
// (object d1, object d2) = (Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyNotAnOutLocal(model, x1Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
var (y1, dd) = (TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var (d, dd) = (TakeOutParam(true, out var x1), x1);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
(var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
public void Scope_Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
lock (Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
lock (Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Dummy(x4);
}
void Test6()
{
lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
lock (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
lock (Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
lock (Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
lock (Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// lock (Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
lock (Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// lock (Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
lock (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,48): error CS0128: A local variable named 'x4' is already defined in this scope
// lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48),
// (35,21): error CS0841: Cannot use local variable 'x6' before it is declared
// lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (60,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19),
// (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52),
// (68,34): error CS0103: The name 'y10' does not exist in the current context
// lock (Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34),
// (86,34): error CS0103: The name 'y12' does not exist in the current context
// lock (Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,45): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
if (true)
lock (Dummy(TakeOutParam(true, out var x1)))
{
}
x1++;
}
static object TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Lock_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@"
lock (Dummy(TakeOutParam(true, out var x1), x1)) ;
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
lock (Dummy(TakeOutParam(""lock"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"lock
lock
lock");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static object Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_ParameterDefault_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out int x4))
{}
void Test5(bool p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0')
Locals: Local_1: System.Int32 x3
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0')
Left:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_ParameterDefault_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out var x4))
{}
void Test5(bool p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out var x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
bool Test5 {get;} = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 {get;} = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,25): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,32): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 {get;} = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void PropertyInitializers_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void PropertyInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,63): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void PropertyInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(new X().Test1);
}
int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Scope_Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
}
void Test2()
{
var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
}
void Test3()
{
var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
void Test6()
{
var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
}
void Test7()
{
var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
}
void Test8()
{
var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
}
void Test9()
{
var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
}
void Test10()
{
var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
}
void Test11()
{
var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,26): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26),
// (27,15): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15),
// (35,32): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32),
// (37,15): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15),
// (45,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35),
// (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35),
// (49,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32),
// (49,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36),
// (52,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15),
// (53,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15),
// (61,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35),
// (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35),
// (66,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32),
// (66,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36),
// (69,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15),
// (70,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15),
// (78,26): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26),
// (80,15): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15),
// (87,27): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27),
// (89,27): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27),
// (91,26): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26),
// (91,31): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31),
// (93,15): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15),
// (94,15): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15),
// (102,15): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15),
// (112,25): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25),
// (109,25): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25),
// (114,15): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15),
// (115,15): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15),
// (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24),
// (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
[Fact]
public void Scope_Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35),
// (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35),
// (22,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32),
// (22,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36),
// (25,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15),
// (26,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15),
// (35,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35),
// (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35),
// (40,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32),
// (40,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36),
// (43,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15),
// (44,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0;
var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0);
Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62),
// (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51),
// (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58),
// (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49),
// (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51),
// (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51),
// (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47),
// (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49),
// (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54),
// (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(3, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVarDuplicateInSameScope(model, yDecl);
VerifyNotAnOutLocal(model, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
}
VerifyNotAnOutLocal(model, yRef[2]);
switch (i)
{
case 12:
VerifyNotAnOutLocal(model, yRef[1]);
break;
default:
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
var y13Decl = GetOutVarDeclarations(tree, "y13").Single();
var y13Ref = GetReference(tree, "y13");
VerifyModelForOutVar(model, y13Decl, y13Ref);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_06()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y1),
TakeOutParam(out int y2),
TakeOutParam(out int y3),
TakeOutParam(out int y4),
TakeOutParam(out int y5),
TakeOutParam(out int y6),
TakeOutParam(out int y7),
TakeOutParam(out int y8),
TakeOutParam(out int y9),
TakeOutParam(out int y10),
TakeOutParam(out int y11),
TakeOutParam(out int y12),
from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62),
// (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51),
// (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58),
// (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49),
// (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51),
// (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51),
// (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47),
// (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49),
// (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54),
// (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
break;
case 12:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
}
}
}
[Fact]
public void Scope_Query_07()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y3),
from x1 in new[] { 0 }
select x1
into x1
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on x1 equals x3
select y3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,62): error CS0128: A local variable named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
const string id = "y3";
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
// Since the name is declared twice in the same scope,
// both references are to the same declaration.
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
}
[Fact]
public void Scope_Query_08()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4)
) ? 1 : 0}
from y1 in new[] { 1 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by x1
into y4
select y4;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// from y1 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24),
// (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24),
// (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23),
// (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 5; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_09()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by 1
into y4
select y4 == null ? 1 : 0
into x2
join y5 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4),
TakeOutParam(out var y5)
) ? 1 : 0 }
on x2 equals y5
select x2;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// var res = from y1 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24),
// (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24),
// (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23),
// (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24),
// (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5'
// join y5 in new[] { Dummy(TakeOutParam(out var y1),
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 6; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
switch (i)
{
case 4:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
case 5:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
default:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
[WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void Scope_Query_10()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
select y1;
}
void Test2()
{
var res = from y2 in new[] { 0 }
join x3 in new[] { 1 }
on TakeOutParam(out var y2) ? y2 : 0
equals x3
select y2;
}
void Test3()
{
var res = from x3 in new[] { 0 }
join y3 in new[] { 1 }
on x3
equals TakeOutParam(out var y3) ? y3 : 0
select y3;
}
void Test4()
{
var res = from y4 in new[] { 0 }
where TakeOutParam(out var y4) && y4 == 1
select y4;
}
void Test5()
{
var res = from y5 in new[] { 0 }
orderby TakeOutParam(out var y5) && y5 > 1,
1
select y5;
}
void Test6()
{
var res = from y6 in new[] { 0 }
orderby 1,
TakeOutParam(out var y6) && y6 > 1
select y6;
}
void Test7()
{
var res = from y7 in new[] { 0 }
group TakeOutParam(out var y7) && y7 == 3
by y7;
}
void Test8()
{
var res = from y8 in new[] { 0 }
group y8
by TakeOutParam(out var y8) && y8 == 3;
}
void Test9()
{
var res = from y9 in new[] { 0 }
let x4 = TakeOutParam(out var y9) && y9 > 0
select y9;
}
void Test10()
{
var res = from y10 in new[] { 0 }
select TakeOutParam(out var y10) && y10 > 0;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052
compilation.VerifyDiagnostics(
// (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59),
// (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(out var y2) ? y2 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48),
// (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(out var y3) ? y3 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52),
// (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(out var y4) && y4 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46),
// (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(out var y5) && y5 > 1,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48),
// (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(out var y6) && y6 > 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48),
// (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(out var y7) && y7 == 3
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46),
// (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(out var y8) && y8 == 3;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43),
// (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x4 = TakeOutParam(out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49),
// (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(out var y10) && y10 > 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 11; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(i == 10 ? 1 : 2, yRef.Length);
switch (i)
{
case 4:
case 6:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
case 8:
VerifyModelForOutVar(model, yDecl, yRef[1]);
VerifyNotAnOutLocal(model, yRef[0]);
break;
case 10:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
}
[Fact]
public void Scope_Query_11()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y1),
from x2 in new [] { y1 }
where TakeOutParam(x1, out var y1)
select x2)
select x1;
}
void Test2()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y2),
TakeOutParam(x1 + 1, out var y2))
select x1;
}
void Test3()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out int y3, y3)
select x1;
}
void Test4()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out var y4, y4)
select x1;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(x1, out var y1)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62),
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal(2, y1Decl.Length);
VerifyModelForOutVar(model, y1Decl[0], y1Ref);
VerifyModelForOutVar(model, y1Decl[1]);
var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray();
Assert.Equal(2, y2Decl.Length);
VerifyModelForOutVar(model, y2Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").Single();
VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").Single();
VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0}
on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0
equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0
where TakeOutParam(6, out var y6) && Print(y6)
orderby TakeOutParam(7, out var y7) && Print(y7),
TakeOutParam(8, out var y8) && Print(y8)
group TakeOutParam(9, out var y9) && Print(y9)
by TakeOutParam(10, out var y10) && Print(y10)
into g
let x11 = TakeOutParam(11, out var y11) && Print(y11)
select TakeOutParam(12, out var y12) && Print(y12);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"1
3
5
2
4
6
7
8
10
9
11
12
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl, yRef);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString());
}
}
[Fact]
public void Query_02()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutVar(model, yDecl, yRef);
}
[Fact]
public void Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in new[] { true }
select a && TakeOutParam(3, out int x1) || x1 > 0;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,62): error CS0165: Use of unassigned local variable 'x1'
// select a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
compilation.VerifyOperationTree(x1Decl, expectedOperationTree:
@"
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
");
}
[Fact]
public void Query_04()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static int Test1()
{
var res = from a in new[] { 1 }
select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
return res.Single();
}
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in (new[] { 1 }).AsQueryable()
select TakeOutParam(a, out int x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,46): error CS8198: An expression tree may not contain an out argument variable declaration.
// select TakeOutParam(a, out int x1);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46)
);
}
[Fact]
public void Scope_ReturnStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null; }
object Test1()
{
return Dummy(TakeOutParam(true, out var x1), x1);
{
return Dummy(TakeOutParam(true, out var x1), x1);
}
return Dummy(TakeOutParam(true, out var x1), x1);
}
object Test2()
{
return Dummy(x2, TakeOutParam(true, out var x2));
}
object Test3(int x3)
{
return Dummy(TakeOutParam(true, out var x3), x3);
}
object Test4()
{
var x4 = 11;
Dummy(x4);
return Dummy(TakeOutParam(true, out var x4), x4);
}
object Test5()
{
return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//object Test6()
//{
// let x6 = 11;
// Dummy(x6);
// return Dummy(TakeOutParam(true, out var x6), x6);
//}
//object Test7()
//{
// return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
object Test8()
{
return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
object Test9(bool y9)
{
if (y9)
return Dummy(TakeOutParam(true, out var x9), x9);
return null;
}
System.Func<object> Test10(bool y10)
{
return () =>
{
if (y10)
return Dummy(TakeOutParam(true, out var x10), x10);
return null;};
}
object Test11()
{
Dummy(x11);
return Dummy(TakeOutParam(true, out var x11), x11);
}
object Test12()
{
return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53),
// (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49),
// (14,13): warning CS0162: Unreachable code detected
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13),
// (21,22): error CS0841: Cannot use local variable 'x2' before it is declared
// return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22),
// (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49),
// (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ReturnStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
int Dummy(params object[] x) { return 0;}
int Test1(bool val)
{
if (val)
return Dummy(TakeOutParam(true, out var x1));
x1++;
return 0;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ReturnStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@"
return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Return_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static object Test()
{
return Dummy(TakeOutParam(""return"", out var x1), x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"return");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Return_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static object Test(bool val)
{
if (val)
return Dummy(TakeOutParam(""return 1"", out var x2), x2);
if (!val)
{
return Dummy(TakeOutParam(""return 2"", out var x2), x2);
}
return null;
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"return 1
return 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
switch (TakeOutParam(1, out var x1) ? x1 : 0)
{
case 0:
Dummy(x1, 0);
break;
}
Dummy(x1, 1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
switch (TakeOutParam(4, out var x4) ? x4 : 0)
{
case 4:
Dummy(x4);
break;
}
}
void Test5(int x5)
{
switch (TakeOutParam(5, out var x5) ? x5 : 0)
{
case 5:
Dummy(x5);
break;
}
}
void Test6()
{
switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
{
case 6:
Dummy(x6);
break;
}
}
void Test7()
{
switch (TakeOutParam(7, out var x7) ? x7 : 0)
{
case 7:
var x7 = 12;
Dummy(x7);
break;
}
}
void Test9()
{
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 0);
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 1);
break;
}
break;
}
}
void Test10()
{
switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
{
case 10:
var y10 = 12;
Dummy(y10);
break;
}
}
//void Test11()
//{
// switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0))
// {
// case 11:
// let y11 = 12;
// Dummy(y11);
// break;
// }
//}
void Test14()
{
switch (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14) ? 1 : 0)
{
case 0:
Dummy(x14);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (27,41): error CS0128: A local variable named 'x4' is already defined in this scope
// switch (TakeOutParam(4, out var x4) ? x4 : 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41),
// (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(5, out var x5) ? x5 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41),
// (47,17): error CS0841: Cannot use local variable 'x6' before it is declared
// switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17),
// (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21),
// (71,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9, 0);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23),
// (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(9, out var x9) ? x9 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49),
// (85,17): error CS0103: The name 'y10' does not exist in the current context
// switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17),
// (108,43): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
switch (TakeOutParam(1, out var x1) ? 1 : 0)
{
case 0:
break;
}
Dummy(x1, 1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,15): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Switch_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@"
switch (Dummy(TakeOutParam(true, out var x1), x1)) {}
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test1(0);
Test1(1);
}
static bool Dummy1(bool val, params object[] x) {return val;}
static T Dummy2<T>(T val, params object[] x) {return val;}
static void Test1(int val)
{
switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1)))
{
case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)):
System.Console.WriteLine(x1, y1);
break;
case int z1:
System.Console.WriteLine(x1, z1);
break;
}
System.Console.WriteLine(x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"Test1 case 0
Test1 {0}
Test1 1
Test1 {0}");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 1 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 2 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(TakeOutParam(true, out var x6), x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(TakeOutParam(true, out var x7), x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(TakeOutParam(true, out var x10), x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(TakeOutParam(true, out var x11), x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(TakeOutParam(true, out var x12), x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x15), x15):
case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Dummy(x15);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58),
// (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58),
// (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58),
// (102,95): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95),
// (112,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31),
// (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58),
// (144,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17),
// (146,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31),
// (147,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23),
// (157,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17),
// (162,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31),
// (163,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23),
// (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58),
// (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58),
// (198,58): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58),
// (198,64): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyNotAnOutLocal(model, x4Ref[3]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAnOutLocal(model, x5Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAnOutLocal(model, x9Ref[0]);
VerifyNotAnOutLocal(model, x9Ref[1]);
VerifyNotAnOutLocal(model, x9Ref[2]);
VerifyNotAnOutLocal(model, x9Ref[3]);
VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_03()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
while (TakeOutParam(x1, out var y1) && Print(y1)) break;
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_04()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
do
val = 0;
while (TakeOutParam(x1, out var y1) && Print(y1));
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_05()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
lock ((object)TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_06()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
if (TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
switch (TakeOutParam(x1, out var y1))
{
default: break;
}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_08()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var x in Test(1)) {}
}
static System.Collections.IEnumerable Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
yield return TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_09()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z1 = x1 > 0 & TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_10()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
a: TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (14,1): warning CS0164: This label has not been referenced
// a: TakeOutParam(x1, out var y1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_11()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
return TakeOutParam(x1, out var y1) && Print(y1);
System.Console.WriteLine(y1);
break;
}
return false;
}
static bool Print<T>(T x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (15,17): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_12()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
try
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
throw Dummy(TakeOutParam(x1, out var y1), y1);
System.Console.WriteLine(y1);
break;
}
}
catch
{}
return false;
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (17,21): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_13()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_14()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelPattern_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test8(object val)
{
switch (val)
{
case int x8
when Dummy(x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case int x13 when Dummy(x13):
Dummy(x13);
break;
}
}
void Test14(object val)
{
switch (val)
{
case int x14 when Dummy(x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test16(object val)
{
switch (val)
{
case int x16 when Dummy(x16):
case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Dummy(x16);
break;
}
}
void Test17(object val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x17), x17):
case int x17 when Dummy(x17):
Dummy(x17);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,64): error CS0128: A local variable named 'x8' is already defined in this scope
// when Dummy(x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64),
// (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x13 when Dummy(x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22),
// (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x14 when Dummy(x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22),
// (51,58): error CS0128: A local variable named 'x16' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58),
// (51,64): error CS0165: Use of unassigned local variable 'x16'
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64),
// (62,22): error CS0128: A local variable named 'x17' is already defined in this scope
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22),
// (62,37): error CS0165: Use of unassigned local variable 'x17'
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyNotAnOutLocal(model, x13Ref[3]);
VerifyNotAnOutLocal(model, x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").Single();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(4, x14Ref.Length);
VerifyNotAnOutLocal(model, x14Ref[0]);
VerifyNotAnOutLocal(model, x14Ref[1]);
VerifyNotAnOutLocal(model, x14Ref[2]);
VerifyNotAnOutLocal(model, x14Ref[3]);
VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x16Decl = GetOutVarDeclarations(tree, "x16").Single();
var x16Ref = GetReferences(tree, "x16").ToArray();
Assert.Equal(3, x16Ref.Length);
for (int i = 0; i < x16Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x16Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x16Decl);
var x17Decl = GetOutVarDeclarations(tree, "x17").Single();
var x17Ref = GetReferences(tree, "x17").ToArray();
Assert.Equal(3, x17Ref.Length);
VerifyModelForOutVar(model, x17Decl, x17Ref);
}
[Fact]
public void Scope_ThrowStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1()
{
throw Dummy(TakeOutParam(true, out var x1), x1);
{
throw Dummy(TakeOutParam(true, out var x1), x1);
}
throw Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
throw Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
throw Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
throw Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
throw Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// throw Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// throw Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
throw Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
throw Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
throw Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
throw Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52),
// (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48),
// (21,21): error CS0841: Cannot use local variable 'x2' before it is declared
// throw Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21),
// (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48),
// (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ThrowStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1(bool val)
{
if (val)
throw Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ThrowStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@"
throw Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Throw_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static void Test()
{
try
{
throw Dummy(TakeOutParam(""throw"", out var x2), x2);
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"throw");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
}
[Fact]
public void Throw_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static void Test(bool val)
{
try
{
if (val)
throw Dummy(TakeOutParam(""throw 1"", out var x2), x2);
if (!val)
{
throw Dummy(TakeOutParam(""throw 2"", out var x2), x2);
}
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"throw 1
throw 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49),
// (35,22): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53),
// (68,35): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35),
// (86,35): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (var d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (var d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (var d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72),
// (35,45): error CS0841: Cannot use local variable 'x6' before it is declared
// using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76),
// (68,58): error CS0103: The name 'y10' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58),
// (86,58): error CS0103: The name 'y12' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,69): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,58): error CS0128: A local variable named 'x1' is already defined in this scope
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (12,63): error CS0841: Cannot use local variable 'x1' before it is declared
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63),
// (20,73): error CS0128: A local variable named 'x2' is already defined in this scope
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73),
// (20,78): error CS0165: Use of unassigned local variable 'x2'
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_Using_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void Scope_While_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
while (TakeOutParam(true, out var x1) && x1)
{
Dummy(x1);
}
}
void Test2()
{
while (TakeOutParam(true, out var x2) && x2)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4)
Dummy(x4);
}
void Test6()
{
while (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
while (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
while (TakeOutParam(true, out var x8) && x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
while (TakeOutParam(true, out var x9) && x9)
{
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9) // 2
Dummy(x9);
}
}
void Test10()
{
while (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// while (TakeOutParam(y11, out var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
while (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// while (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
void Test14()
{
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47),
// (68,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29),
// (86,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_While_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
while (TakeOutParam(true, out var x1))
{
;
}
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_While_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@"
while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void While_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
f = false;
f = true;
if (f)
{
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
4");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void While_03()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_05()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
1
2
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Yield_01()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
IEnumerable Test2()
{
yield return Dummy(x2, TakeOutParam(true, out var x2));
}
IEnumerable Test3(int x3)
{
yield return Dummy(TakeOutParam(true, out var x3), x3);
}
IEnumerable Test4()
{
var x4 = 11;
Dummy(x4);
yield return Dummy(TakeOutParam(true, out var x4), x4);
}
IEnumerable Test5()
{
yield return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//IEnumerable Test6()
//{
// let x6 = 11;
// Dummy(x6);
// yield return Dummy(TakeOutParam(true, out var x6), x6);
//}
//IEnumerable Test7()
//{
// yield return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
IEnumerable Test8()
{
yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
IEnumerable Test9(bool y9)
{
if (y9)
yield return Dummy(TakeOutParam(true, out var x9), x9);
}
IEnumerable Test11()
{
Dummy(x11);
yield return Dummy(TakeOutParam(true, out var x11), x11);
}
IEnumerable Test12()
{
yield return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59),
// (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55),
// (23,28): error CS0841: Cannot use local variable 'x2' before it is declared
// yield return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28),
// (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55),
// (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55),
// (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13),
// (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13),
// (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92),
// (72,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_Yield_02()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
IEnumerable Test1()
{
if (true)
yield return TakeOutParam(true, out var x1);
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Yield_03()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
IEnumerable Test1()
{
yield return 0;
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@"
yield return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Yield_01()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
yield return Dummy(TakeOutParam(""yield2"", out var x2), x2);
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2
yield1");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Yield_02()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
bool f = true;
if (f)
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
if (f)
{
yield return Dummy(TakeOutParam(""yield2"", out var x1), x1);
}
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_LabeledStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
a: Dummy(TakeOutParam(true, out var x1), x1);
{
b: Dummy(TakeOutParam(true, out var x1), x1);
}
c: Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
a: Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
a: Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
a: Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
a: Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
//a: Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
//a: Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
a: Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
a: Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
a: Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
a: Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (12,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1),
// (14,1): warning CS0164: This label has not been referenced
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1),
// (16,1): warning CS0164: This label has not been referenced
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (21,1): warning CS0164: This label has not been referenced
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (26,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (33,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (38,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x5), x5);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (59,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1),
// (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1),
// (65,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1),
// (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1),
// (73,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (80,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x11), x11);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1),
// (85,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x12), x12);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_LabeledStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
a: Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1),
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9),
// (13,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_LabeledStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@"
a: b: Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Labeled_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
a: b: c:Test2(Test1(out int x1), x1);
System.Console.Write(x1);
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(
// (11,1): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1),
// (11,4): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4),
// (11,7): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Labeled_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
{
a: Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(
// (15,1): warning CS0164: This label has not been referenced
// a: Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void DataFlow_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
x1);
}
static void Test(out int x, int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
ref x1);
}
static void Test(out int x, ref int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// ref x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
var x2 = 1;
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used
// var x2 = 1;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single();
var dataFlow = model.AnalyzeDataFlow(x2Decl);
Assert.True(dataFlow.Succeeded);
Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString());
Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString());
}
[Fact]
public void TypeMismatch_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
}
static void Test(out short x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short'
// Test(out int x1);
Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(int x1);
Test(ref int x2);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,14): error CS1525: Invalid expression term 'int'
// Test(int x1);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// Test(int x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22),
// (6,18): error CS0103: The name 'x1' does not exist in the current context
// Test(int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18),
// (7,22): error CS0103: The name 'x2' does not exist in the current context
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void Parse_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1.);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,24): error CS1003: Syntax error, ',' expected
// Test(out int x1.);
Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out System.Collections.Generic.IEnumerable<System.Int32>);
}
static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable
// Test(out System.Collections.Generic.IEnumerable<System.Int32>);
Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void GetAliasInfo_01()
{
var text = @"
using a = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out a x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GetAliasInfo_02()
{
var text = @"
using var = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void VarIsNotVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out var x)
{
x = new var() {val = 123};
return null;
}
static void Test2(object x, var y)
{
System.Console.WriteLine(y.val);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void VarIsNotVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test1' does not exist in the current context
// Test1(out var x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9),
// (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0
// public int val;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void SimpleVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static void Test2(object x, object y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0103: The name 'Test1' does not exist in the current context
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
out x1);
}
static object Test1(out int x, out int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// out x1);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
Test1(out x1,
3));
}
static object Test1(out int x, int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// Test1(out x1,
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(ref int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic x = null;
Test2(x.Test1(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x.Test1(out var x1),
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var x1), x1);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new System.Action(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,37): error CS0149: Method name expected
// Test2(new System.Action(out var x1),
Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x, object y)
{
System.Console.WriteLine(y);
}
public Test2()
: this(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : this(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26)
);
var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
var typeInfo = model.GetTypeInfo(initializer);
var symbolInfo = model.GetSymbolInfo(initializer);
var group = model.GetMemberGroup(initializer);
Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936
}
[Fact]
public void ConstructorInitializers_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
public Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}
class Test3 : Test2
{
public Test3()
: base(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : base(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26)
);
}
[Fact]
public void ConstructorInitializers_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
class Test2
{
Test2(out int x)
{
x = 2;
}
public Test2()
: this(out var x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
class Test2
{
public Test2(out int x)
{
x = 1;
}
}
class Test3 : Test2
{
public Test3()
: base(out var x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void ConstructorInitializers_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(System.Func<object> x)
{
System.Console.WriteLine(x());
}
public Test2()
: this(() =>
{
Test1(out var x1);
return x1;
})
{}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (23,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(23, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer();
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular)
.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.True(analyzer.ActionFired);
}
private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer
{
public bool ActionFired { get; private set; }
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.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer);
}
private void Handle(SyntaxNodeAnalysisContext context)
{
ActionFired = true;
var tree = context.Node.SyntaxTree;
var model = context.SemanticModel;
var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent;
SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model);
Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration));
MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration];
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0]));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1]));
}
}
[Fact]
public void ConstructorInitializers_09()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_10()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_11()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (21,37): error CS0165: Use of unassigned local variable 'x1'
// => System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_12()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_13()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_14()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_15()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_16()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_17()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_14()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_15()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var var), var);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var varDecl = GetOutVarDeclaration(tree, "var");
var varRef = GetReferences(tree, "var").Skip(1).Single();
VerifyModelForOutVar(model, varDecl, varRef);
}
[Fact]
public void SimpleVar_16()
{
var text = @"
public class Cls
{
public static void Main()
{
if (Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
static bool Test1(out int x)
{
x = 123;
return true;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void VarAndBetterness_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
Test2(out var x2, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, string y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
static object Test2(out int x, string y)
{
x = 125;
System.Console.WriteLine(x);
return null;
}
static object Test2(out short x, object y)
{
x = 126;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
VerifyModelForOutVar(model, x2Decl);
}
[Fact]
public void VarAndBetterness_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, object y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)'
// Test1(out var x1, null);
Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.ArgIterator x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_03()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async void Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void RestrictedTypes_04()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out System.ArgIterator x1), x1);
var x = default(System.ArgIterator);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
targetFramework: TargetFramework.Mscorlib45,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out System.ArgIterator x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// var x = default(System.ArgIterator);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9),
// (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async void Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ElementAccess_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out var x1]);
Test2(x1);
Test2(x[out var _]);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25),
// (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21),
// (9,21): error CS8183: Cannot infer the type of implicitly-typed discard.
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21)
);
}
[Fact]
public void PointerAccess_01()
{
var text = @"
public class Cls
{
public static unsafe void Main()
{
int* p = (int*)0;
Test2(p[out var x1]);
Test2(x1);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25)
);
}
[Fact]
public void ElementAccess_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out int x1], x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21)
);
}
[Fact]
[WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")]
public void MissingArgumentAndNamedOutVarArgument()
{
var source =
@"class Program
{
public static void Main(string[] args)
{
if (M(s: out var s))
{
string s2 = s;
}
}
public static bool M(int i, out string s)
{
s = i.ToString();
return true;
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)'
// if (M(s: out var s))
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13)
);
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x);
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out int x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
for (var y = Test1(out var x) + x; y != 0 ; y = 0)
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
foreach (var y in new [] {Test1(out var x) + x})
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(x: 1, out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21),
// (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
int x = 0;
Test1(y: ref x, y: out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)'
// Test1(y: ref x, y: out var y);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
var yRef = GetReferences(tree, "y").ToArray();
Assert.Equal(3, yRef.Length);
Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString());
VerifyModelForOutVar(model, yDecl, yRef[2]);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamic()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int z];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1) //z
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}");
}
[Fact]
public void IndexingDynamicWithDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"
{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}
");
}
[Fact]
public void IndexingDynamicWithVarDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef });
comp.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out var _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23)
);
}
[Fact]
public void IndexingDynamicWithShortDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out _];
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutVar()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.True(x1.Type.IsErrorType());
VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var x = d[out var x1] + x1;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutInt()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation.VerifyDiagnostics();
}
[ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void OutVariableDeclarationInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; return 2;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.2
ret
}
// i = 3; return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.3
stind.i4
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 4; return 5;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.5
ret
}
// i = 6; return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.6
stind.i4
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} x1] + "" "" + x1);
ia.P[out {0} x2] = 4;
Console.WriteLine(x2);
Console.WriteLine(ia[out {0} x3] + "" "" + x3);
ia[out {0} x4] = 4;
Console.WriteLine(x4);
}}
}}";
string[] fillIns = new[] { "int", "var" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 });
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString());
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString());
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(1, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString());
CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput:
@"2 1
3
5 4
6")
.VerifyIL("B.Main()",
@"{
// Code size 113 (0x71)
.maxstack 4
.locals init (int V_0, //x1
int V_1, //x2
int V_2, //x3
int V_3, //x4
int V_4)
IL_0000: newobj ""A..ctor()""
IL_0005: dup
IL_0006: ldloca.s V_0
IL_0008: callvirt ""int IA.P[out int].get""
IL_000d: stloc.s V_4
IL_000f: ldloca.s V_4
IL_0011: call ""string int.ToString()""
IL_0016: ldstr "" ""
IL_001b: ldloca.s V_0
IL_001d: call ""string int.ToString()""
IL_0022: call ""string string.Concat(string, string, string)""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: dup
IL_002d: ldloca.s V_1
IL_002f: ldc.i4.4
IL_0030: callvirt ""void IA.P[out int].set""
IL_0035: ldloc.1
IL_0036: call ""void System.Console.WriteLine(int)""
IL_003b: dup
IL_003c: ldloca.s V_2
IL_003e: callvirt ""int IA.this[out int].get""
IL_0043: stloc.s V_4
IL_0045: ldloca.s V_4
IL_0047: call ""string int.ToString()""
IL_004c: ldstr "" ""
IL_0051: ldloca.s V_2
IL_0053: call ""string int.ToString()""
IL_0058: call ""string string.Concat(string, string, string)""
IL_005d: call ""void System.Console.WriteLine(string)""
IL_0062: ldloca.s V_3
IL_0064: ldc.i4.4
IL_0065: callvirt ""void IA.this[out int].set""
IL_006a: ldloc.3
IL_006b: call ""void System.Console.WriteLine(int)""
IL_0070: ret
}");
}
}
[ClrOnlyFact]
public void OutVariableDiscardInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; System.Console.WriteLine(11); return 111;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.s 11
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x06F
ret
}
// i = 2; System.Console.Write(22); return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.2
stind.i4
ldc.i4.s 22
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 3; System.Console.WriteLine(33) return 333;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.3
stind.i4
ldc.i4.s 33
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x14D
ret
}
// i = 4; System.Console.WriteLine(44); return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.s 44
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} _]);
ia.P[out {0} _] = 4;
Console.WriteLine(ia[out {0} _]);
ia[out {0} _] = 4;
}}
}}";
string[] fillIns = new[] { "int", "var", "" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"11
111
22
33
333
44")
.VerifyIL("B.Main()",
@"
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (A V_0, //a
IA V_1, //ia
int V_2)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloca.s V_2
IL_000c: callvirt ""int IA.P[out int].get""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ldloc.1
IL_0018: ldloca.s V_2
IL_001a: ldc.i4.4
IL_001b: callvirt ""void IA.P[out int].set""
IL_0020: nop
IL_0021: ldloc.1
IL_0022: ldloca.s V_2
IL_0024: callvirt ""int IA.this[out int].get""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ldloc.1
IL_0030: ldloca.s V_2
IL_0032: ldc.i4.4
IL_0033: callvirt ""void IA.this[out int].set""
IL_0038: nop
IL_0039: ret
}");
}
}
[Fact]
public void ElementAccess_04()
{
var text = @"
using System.Collections.Generic;
public class Cls
{
public static void Main()
{
var list = new Dictionary<int, long>
{
[out var x1] = 3,
[out var _] = 4,
[out _] = 5
};
System.Console.Write(x1);
System.Console.Write(_);
{
int _ = 1;
var list2 = new Dictionary<int, long> { [out _] = 6 };
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var x1] = 3,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18),
// (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var _] = 4,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18),
// (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out _] = 5
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18),
// (14,30): error CS0103: The name '_' does not exist in the current context
// System.Console.Write(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30),
// (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var list2 = new Dictionary<int, long> { [out _] = 6 };
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58)
);
}
[Fact]
public void ElementAccess_05()
{
var text = @"
public class Cls
{
public static void Main()
{
int[out var x1] a = null; // fatal syntax error - 'out' is skipped
int b(out var x2) = null; // parsed as a local function with syntax error
int c[out var x3] = null; // fatal syntax error - 'out' is skipped
int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
x4 = 0;
}
}";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count());
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
compilation.VerifyDiagnostics(
// (6,13): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13),
// (6,21): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21),
// (7,27): error CS1002: ; expected
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27),
// (7,27): error CS1525: Invalid expression term '='
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27),
// (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14),
// (8,15): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15),
// (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19),
// (8,23): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23),
// (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23),
// (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17),
// (10,17): error CS1003: Syntax error, '[' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17),
// (10,28): error CS1003: Syntax error, ']' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28),
// (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12),
// (6,17): error CS0103: The name 'var' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17),
// (6,21): error CS0103: The name 'x1' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21),
// (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body.
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13),
// (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19),
// (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29),
// (8,19): error CS0103: The name 'var' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19),
// (8,23): error CS0103: The name 'x3' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23),
// (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13),
// (6,25): warning CS0219: The variable 'a' is assigned but its value is never used
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25),
// (10,13): warning CS0168: The variable 'd' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13),
// (10,16): warning CS0168: The variable 'e' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16),
// (7,13): warning CS8321: The local function 'b' is declared but never used
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13)
);
}
[Fact]
public void ElementAccess_06()
{
var text = @"
public class Cls
{
public static void Main()
{
{
int[] e = null;
var z1 = e?[out var x1];
x1 = 1;
}
{
int[][] e = null;
var z2 = e?[out var x2]?[out var x3];
x2 = 1;
x3 = 2;
}
{
int[][] e = null;
var z3 = e?[0]?[out var x4];
x4 = 1;
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var x2Decl = GetOutVarDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29),
// (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33),
// (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29),
// (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'.
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33),
// (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33),
// (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'.
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37)
);
}
[Fact]
public void FixedFieldSize()
{
var text = @"
unsafe struct S
{
fixed int F1[out var x1, x1];
//fixed int F2[3 is int x2 ? x2 : 3];
//fixed int F2[3 is int x3 ? 3 : 3, x3];
}
";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Empty(GetOutVarDeclarations(tree, "x1"));
compilation.VerifyDiagnostics(
// (4,18): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18),
// (4,26): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26),
// (4,17): error CS7092: A fixed buffer may only have one dimension.
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17),
// (4,22): error CS0103: The name 'var' does not exist in the current context
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22)
);
}
[Fact]
public void Scope_DeclaratorArguments_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
int d,e(Dummy(TakeOutParam(true, out var x1), x1));
}
void Test4()
{
var x4 = 11;
Dummy(x4);
int d,e(Dummy(TakeOutParam(true, out var x4), x4));
}
void Test6()
{
int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
}
void Test8()
{
int d,e(Dummy(TakeOutParam(true, out var x8), x8));
System.Console.WriteLine(x8);
}
void Test14()
{
int d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// int d,e(Dummy(TakeOutParam(true, out var x4), x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (30,34): error CS0165: Use of unassigned local variable 'x8'
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl)
{
Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl));
}
private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls)
{
foreach (var decl in decls)
{
AssertContainedInDeclaratorArguments(decl);
}
}
[Fact]
public void Scope_DeclaratorArguments_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d, x1(
Dummy(TakeOutParam(true, out var x1), x1));
Dummy(x1);
}
void Test2()
{
object d, x2(
Dummy(TakeOutParam(true, out var x2), x2));
Dummy(x2);
}
void Test3()
{
object x3, d(
Dummy(TakeOutParam(true, out var x3), x3));
Dummy(x3);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,13): error CS0818: Implicitly-typed variables must be initialized
// var d, x1(
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13),
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (21,15): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15),
// (27,54): error CS0128: A local variable named 'x3' is already defined in this scope
// Dummy(TakeOutParam(true, out var x3), x3));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54),
// (28,15): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1( Dummy(x1));
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2(Dummy(x3));
}
void Test4()
{
object d1,e(Dummy(x4)],
d2(Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1( Dummy(x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (14,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1,e(Dummy(x4)],
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 (Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (13,27): error CS0165: Use of unassigned local variable 'x1'
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59),
// (26,27): error CS0165: Use of unassigned local variable 'x3'
// d2 = Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y, y1(Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single();
Assert.Equal("var y1", y1.ToTestDisplayString());
Assert.True(((ILocalSymbol)y1).Type.IsErrorType());
}
[Fact]
public void Scope_DeclaratorArguments_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d,e(TakeOutParam(true, out var x1) && x1 != null);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13),
// (11,17): error CS0818: Implicitly-typed variables must be initialized
// var d,e(TakeOutParam(true, out var x1) && x1 != null);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e);
Assert.Equal("var e", symbol.ToTestDisplayString());
Assert.True(symbol.Type.IsErrorType());
}
[Fact]
[WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")]
public void Scope_DeclaratorArguments_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)];
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
AssertContainedInDeclaratorArguments(y1Decl);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType());
}
[Fact]
[WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")]
public void Scope_DeclaratorArguments_08()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x1) && x1)
);;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x2) && x2)
);;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool a, b(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
Dummy(x4);
}
void Test6()
{
for (bool a, b(
Dummy(x6 && TakeOutParam(true, out var x6))
);;)
Dummy(x6);
}
void Test7()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x8) && x8)
);;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool a1, b1(
Dummy(TakeOutParam(true, out var x9) && x9)
);;)
{
Dummy(x9);
for (bool a2, b2(
Dummy(TakeOutParam(true, out var x9) && x9) // 2
);;)
Dummy(x9);
}
}
void Test10()
{
for (bool a, b(
Dummy(TakeOutParam(y10, out var x10))
);;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y11, out var x11))
// );;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool a, b(
Dummy(TakeOutParam(y12, out var x12))
);;)
var y12 = 12;
}
//void Test13()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y13, out var x13))
// );;)
// let y13 = 12;
//}
void Test14()
{
for (bool a, b(
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
);;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_09()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
for (bool d, x4(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
{}
}
void Test7()
{
for (bool x7 = true, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{}
}
void Test8()
{
for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)],
b2(Dummy(TakeOutParam(true, out var x8) && x8));
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2(Dummy(TakeOutParam(true, out var x9) && x9));
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47),
// (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47),
// (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used
// for (bool x7 = true, b(
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19),
// (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2(Dummy(TakeOutParam(true, out var x8) && x8));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52),
// (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47),
// (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47),
// (37,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23),
// (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47),
// (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl[0]);
AssertContainedInDeclaratorArguments(x8Decl[1]);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]);
}
[Fact]
public void Scope_DeclaratorArguments_10()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,e(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (var d,e(Dummy(TakeOutParam(true, out var x2), x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Dummy(x4);
}
void Test6()
{
using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d,e(Dummy(TakeOutParam(true, out var x8), x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d,a(Dummy(TakeOutParam(true, out var x9), x9)))
{
Dummy(x9);
using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
var y12 = 12;
}
//void Test13()
//{
// using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13)))
// let y13 = 12;
//}
void Test14()
{
using (var d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
AssertContainedInDeclaratorArguments(x10Decl);
VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_11()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope
// using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
AssertContainedInDeclaratorArguments(x2Decl);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_DeclaratorArguments_12()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2(Dummy(TakeOutParam(true, out var x4), x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_13()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Dummy(x4);
}
void Test6()
{
fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9)))
{
Dummy(x9);
fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11))))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13))))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_14()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* d,x1(
Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)],
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p(Dummy(TakeOutParam(true, out var x3) && x3)))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)],
p2(Dummy(TakeOutParam(true, out var x4) && x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_15()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
bool Test4 [x4 && TakeOutParam(4, out var x4)];
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
private static void VerifyModelNotSupported(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax));
Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var identifierText = decl.Identifier().ValueText;
Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any());
Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText));
Assert.Null(model.GetSymbolInfo(decl.Type).Symbol);
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null);
VerifyModelNotSupported(model, references);
}
private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart));
Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType());
}
}
[Fact]
public void Scope_DeclaratorArguments_16()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
fixed
bool Test4 [x4 && TakeOutParam(4, out var x4)];
fixed
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
fixed
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
fixed
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
fixed
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField,
(int)ErrorCode.ERR_NoImplicitConv
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 [x4 && TakeOutParam(4, out var x4)];
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (20,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 [Dummy(x7, 2)];
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25),
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_17()
{
var source =
@"
public class X
{
public static void Main()
{
}
const
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
const
bool Test4 [x4 && TakeOutParam(4, out var x4)];
const
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
const
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
const
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
const
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_18()
{
var source =
@"
public class X
{
public static void Main()
{
}
event
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
event
bool Test4 [x4 && TakeOutParam(4, out var x4)];
event
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
event
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
event
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
event
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.ERR_EventNotDelegate,
(int)ErrorCode.WRN_UnreferencedEvent
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_19()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool d[2], Test3 (out var x3);
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (8,28): error CS1003: Syntax error, '[' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28),
// (8,39): error CS1003: Syntax error, ']' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39),
// (8,33): error CS8185: A declaration is not allowed in this context.
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_20()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool Test3[out var x3];
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,22): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22),
// (8,30): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30),
// (8,21): error CS7092: A fixed buffer may only have one dimension.
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21),
// (8,26): error CS0103: The name 'var' does not exist in the current context
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
}
[Fact]
public void StaticType()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out StaticType x1);
}
static object Test1(out StaticType x)
{
throw new System.NotSupportedException();
}
static class StaticType {}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters
// static object Test1(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19),
// (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType'
// Test1(out StaticType x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19)
);
}
[Fact]
public void GlobalCode_Catch_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34),
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42),
// (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13),
// (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Catch_02()
{
var source =
@"
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Block_01()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
}
object x2;
{
H.TakeOutParam(2, out var x2);
H.Dummy(x2);
}
{
H.TakeOutParam(3, out var x3);
}
H.Dummy(x3);
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,8): warning CS0168: The variable 'x2' is declared but never used
// object x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8),
// (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31),
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
}
[Fact]
public void GlobalCode_Block_02()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
System.Console.WriteLine(x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_For_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
for ( // 2
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42),
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_For_02()
{
var source =
@"
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_Foreach_01()
{
var source =
@"using static Helpers;
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
static class Helpers
{
public static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
public static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Foreach_02()
{
var source =
@"
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0));
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) &&
TakeOutParam(o2, out var x5) &&
x5 > 0));
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0));
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0),
x7);
Dummy(x7, 2);
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out var x9) &&
x9 > 0), x9);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) &&
x11 > 0), x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutField(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutField(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutField(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7),
// (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7),
// (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79),
// (37,9): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9),
// (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13),
// (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void GlobalCode_Lambda_02()
{
var source =
@"
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
System.Console.WriteLine(l());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_03()
{
var source =
@"
System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Query_01()
{
var source =
@"
using System.Linq;
bool Dummy(params object[] x) {return true;}
var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutField(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutField(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutField(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutField(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutField(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutField(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutField(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutField(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutField(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutField(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutField(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutField(model, y10Decl, y10Ref[0]);
VerifyNotAnOutField(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutField(model, y11Decl, y11Ref[0]);
VerifyNotAnOutField(model, y11Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7),
// (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18),
// (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
}
[Fact]
public void GlobalCode_Query_02()
{
var source =
@"
using System.Linq;
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutField(model, yDecl, yRef);
}
[Fact]
public void GlobalCode_Using_01()
{
var source =
@"
System.IDisposable Dummy(params object[] x) {return null;}
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_Using_02()
{
var source =
@"
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void GlobalCode_ExpressionStatement_01()
{
string source =
@"
H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out int x2);
H.TakeOutParam(3, out int x3);
object x3;
H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
private static void AssertNoGlobalStatements(SyntaxTree tree)
{
Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>());
}
[Fact]
public void GlobalCode_ExpressionStatement_02()
{
string source =
@"
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out var x2);
H.TakeOutParam(3, out var x3);
object x3;
H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ExpressionStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_IfStatement_01()
{
string source =
@"
if (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out int x2)) {}
if (H.TakeOutParam(3, out int x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
if (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
int x6 = 6;
if (H.Dummy())
{
string x6 = ""6"";
H.Dummy(x6);
}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (30,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17),
// (30,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21),
// (30,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used
// int x6 = 6;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5),
// (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// string x6 = "6";
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12),
// (33,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_IfStatement_02()
{
string source =
@"
if (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out var x2)) {}
if (H.TakeOutParam(3, out var x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
if (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,29): error CS0841: Cannot use local variable 'x5' before it is declared
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29),
// (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
}
[Fact]
public void GlobalCode_IfStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_IfStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_YieldReturnStatement_01()
{
string source =
@"
yield return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out int x2);
yield return H.TakeOutParam(3, out int x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_YieldReturnStatement_02()
{
string source =
@"
yield return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out var x2);
yield return H.TakeOutParam(3, out var x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_01()
{
string source =
@"
return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out int x2);
return H.TakeOutParam(3, out int x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_02()
{
string source =
@"
return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out var x2);
return H.TakeOutParam(3, out var x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
Test();
return H.Dummy(H.TakeOutParam(1, out var x1), x1);
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool Dummy(object x, object y)
{
System.Console.WriteLine(y);
return true;
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_ThrowStatement_01()
{
string source =
@"
throw H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out int x2);
throw H.TakeOutParam(3, out int x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ThrowStatement_02()
{
string source =
@"
throw H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out var x2);
throw H.TakeOutParam(3, out var x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_01()
{
string source =
@"
switch (H.TakeOutParam(1, out int x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out int x2)) {default: break;}
switch (H.TakeOutParam(3, out int x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {default: break;}
switch (H.TakeOutParam(51, out int x5))
{
default:
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_02()
{
string source =
@"
switch (H.TakeOutParam(1, out var x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out var x2)) {default: break;}
switch (H.TakeOutParam(3, out var x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {default: break;}
switch (H.TakeOutParam(51, out var x5))
{
default:
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
switch (H.TakeOutParam(1, out var x1))
{
default:
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
break;
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_WhileStatement_01()
{
string source =
@"
while (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out int x2)) {}
while (H.TakeOutParam(3, out int x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
while (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out int x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_02()
{
string source =
@"
while (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out var x2)) {}
while (H.TakeOutParam(3, out var x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
while (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out var x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_03()
{
string source =
@"
while (H.TakeOutParam(1, out var x1))
{
System.Console.WriteLine(x1);
break;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_DoStatement_01()
{
string source =
@"
do {} while (H.TakeOutParam(1, out int x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out int x2));
do {} while (H.TakeOutParam(3, out int x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4)));
do
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out int x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out int x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out int x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_02()
{
string source =
@"
do {} while (H.TakeOutParam(1, out var x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out var x2));
do {} while (H.TakeOutParam(3, out var x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4)));
do
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out var x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out var x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out var x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_03()
{
string source =
@"
int f = 1;
do
{
}
while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3);
int Test(int x)
{
System.Console.WriteLine(x);
return x;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_LockStatement_01()
{
string source =
@"
lock (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out int x2)) {}
lock (H.TakeOutParam(3, out int x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
lock (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_02()
{
string source =
@"
lock (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out var x2)) {}
lock (H.TakeOutParam(3, out var x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
lock (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_LockStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_DeconstructionDeclarationStatement_01()
{
string source =
@"
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (16,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref[0]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_01()
{
string source =
@"
a: H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out int x2);
c: H.TakeOutParam(3, out int x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_02()
{
string source =
@"
a: H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out var x2);
c: H.TakeOutParam(3, out var x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_04()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out int x2);
e:
bool f = H.TakeOutParam(3, out int x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
i:
bool x5 = H.TakeOutParam(5, out int x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_05()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out var x2);
e:
bool f = H.TakeOutParam(3, out var x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
i:
bool x5 = H.TakeOutParam(5, out var x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void GlobalCode_LabeledStatement_06_Script()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_06_SimpleProgram()
{
string source =
@"
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(compilation, expectedOutput:
@"1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_07()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_08()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out var x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out var x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
H.TakeOutParam(6, out var x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_09()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var (d, e) = (H.TakeOutParam(1, out var x1), 1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_01()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out int x2);
bool f = H.TakeOutParam(3, out int x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 =
H.TakeOutParam(5, out int x5);
bool i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_02()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out var x2);
bool f = H.TakeOutParam(3, out var x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 =
H.TakeOutParam(5, out var x5);
bool i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static var b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_05()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_06()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_07()
{
string source =
@"
Test();
bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
bool Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return false;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_01()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out int x2);
bool f { get; } = H.TakeOutParam(3, out int x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 { get; } =
H.TakeOutParam(5, out int x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_02()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out var x2);
bool f { get; } = H.TakeOutParam(3, out var x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 { get; } =
H.TakeOutParam(5, out var x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
bool d { get; set; } = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static bool b { get; } = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_05()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_06()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_01()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out int x2);
event System.Action f = H.TakeOutParam(3, out int x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
event System.Action x5 =
H.TakeOutParam(5, out int x5);
event System.Action i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_02()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out var x2);
event System.Action f = H.TakeOutParam(3, out var x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
event System.Action x5 =
H.TakeOutParam(5, out var x5);
event System.Action i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
event System.Action d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static event System.Action b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_05()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_06()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_07()
{
string source =
@"
Test();
event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
System.Action Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_DeclaratorArguments_01()
{
string source =
@"
bool a, b(out var x1);
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_02()
{
string source =
@"
label:
bool a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1),
// (4,9): error CS0165: Use of unassigned local variable 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_03()
{
string source =
@"
event System.Action a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_04()
{
string source =
@"
fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static int TakeOutParam<T>(T y, out T x)
{
x = y;
return 3;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"),
parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to 'b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12),
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_RestrictedType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out System.ArgIterator x2);
class H
{
public static void TakeOutParam(out System.ArgIterator x)
{
x = default(System.ArgIterator);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// public static void TakeOutParam(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37),
// (5,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out System.ArgIterator x2);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20),
// (3,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_StaticType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out StaticType x2);
class H
{
public static void TakeOutParam(out StaticType x)
{
x = default(System.ArgIterator);
}
}
static class StaticType{}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (5,31): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out StaticType x2);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31),
// (9,24): error CS0721: 'StaticType': static types cannot be used as parameters
// public static void TakeOutParam(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24),
// (3,24): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_InferenceFailure_01()
{
string source =
@"
H.TakeOutParam(out var x1, x1);
class H
{
public static void TakeOutParam(out int x, long y)
{
x = 1;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.TakeOutParam(out var x1, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact]
public void GlobalCode_InferenceFailure_02()
{
string source =
@"
var a = b;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_03()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = a;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = a;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_04()
{
string source =
@"
var a = x1;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single());
Assert.True(a.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32)
);
}
[Fact]
public void GlobalCode_InferenceFailure_05()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = x1;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = H.TakeOutParam(out var x1, b);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single();
var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl);
Assert.True(b.Type.IsErrorType());
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
Assert.False(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
}
[Fact]
public void GlobalCode_InferenceFailure_06()
{
string source =
@"
H.TakeOutParam(out var x1);
class H
{
public static int TakeOutParam<T>(out T x)
{
x = default(T);
return 123;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24),
// (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")]
public void GlobalCode_InferenceFailure_07()
{
string source =
@"
H.M((var x1, int x2));
H.M(x1);
class H
{
public static void M(object a) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10),
// (2,6): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6),
// (2,14): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14),
// (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5),
// (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object'
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")]
public void InferenceFailure_01()
{
string source =
@"
class H
{
object M1() => M(M(1), x1);
static object M(object o1) => o1;
static void M(object o1, object o2) {}
}
";
var node0 = SyntaxFactory.ParseCompilationUnit(source);
var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
var decl = SyntaxFactory.DeclarationExpression(
type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")),
designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1")));
var node1 = node0.ReplaceNode(one, decl);
var tree = node1.SyntaxTree;
Assert.NotNull(tree);
var compilation = CreateCompilation(new[] { tree });
compilation.VerifyDiagnostics(
// (4,24): error CS8185: A declaration is not allowed in this context.
// object M1() => M(M(varx1), x1);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24)
);
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_AliasInfo_01()
{
string source =
@"
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void GlobalCode_AliasInfo_02()
{
string source =
@"
using var = System.Int32;
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_03()
{
string source =
@"
using a = System.Int32;
H.TakeOutParam(1, out a x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_04()
{
string source =
@"
H.TakeOutParam(1, out int x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_1()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out var x1):
System.Console.WriteLine(x1);
break;
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case !TakeOutParam(3, out var x1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_2()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out UndeclaredType x1):
System.Console.WriteLine(x1);
break;
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19),
// (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?)
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, false, references);
}
private static void VerifyModelForOutFieldDuplicate(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, true, references);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool duplicate,
params IdentifierNameSyntax[] references)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(SymbolKind.Field, symbol.Kind);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText);
var names = model.LookupNames(decl.SpanStart);
if (duplicate)
{
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, symbols.Single());
}
Assert.Contains(decl.Identifier().ValueText, names);
var local = (IFieldSymbol)symbol;
var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement &&
(declarator.ArgumentList?.Contains(decl)).GetValueOrDefault();
// We're not able to get type information at such location (out var argument in global code) at this point
// See https://github.com/dotnet/roslyn/issues/13569
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type);
foreach (var reference in references)
{
var referenceInfo = model.GetSymbolInfo(reference);
symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText);
if (duplicate)
{
Assert.Null(referenceInfo.Symbol);
Assert.Contains(symbol, referenceInfo.CandidateSymbols);
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, referenceInfo.Symbol);
Assert.Same(symbol, symbols.Single());
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
}
if (!inFieldDeclaratorArgumentlist)
{
var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent;
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
}
else
{
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (dataFlow.Succeeded)
{
Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
}
[Fact]
public void MethodTypeArgumentInference_01()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out int a);
TakeOutParam(out long b);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int64");
}
[Fact]
public void MethodTypeArgumentInference_02()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var a);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out var a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_03()
{
var source =
@"
public class X
{
public static void Main()
{
long a = 0;
TakeOutParam(out int b, a);
int c;
TakeOutParam(out c, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out int b, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9),
// (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out c, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_04()
{
var source =
@"
public class X
{
public static void Main()
{
byte a = 0;
int b = 0;
TakeOutParam(out int c, a);
TakeOutParam(out b, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int32");
}
[Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")]
public void OutVarDeclaredInReceiverUsedInArgument()
{
var source =
@"using System.Linq;
public class C
{
public string[] Goo2(out string x) { x = """"; return null; }
public string[] Goo3(bool b) { return null; }
public string[] Goo5(string u) { return null; }
public void Test()
{
var t1 = Goo2(out var x1).Concat(Goo5(x1));
var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First()));
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
}
[Fact]
public void OutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(out int _);
M(out var _);
M(out _);
}
static void M(out int x) { x = 1; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.Single();
var model = comp.Compilation.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetTypeInfo(discard1).Type);
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetTypeInfo(discard2).Type);
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard3));
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
comp.VerifyIL("C.Main()", @"
{
// Code size 22 (0x16)
.maxstack 1
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: call ""void C.M(out int)""
IL_0007: ldloca.s V_0
IL_0009: call ""void C.M(out int)""
IL_000e: ldloca.s V_0
IL_0010: call ""void C.M(out int)""
IL_0015: ret
}
");
}
[Fact]
public void NamedOutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(y: out string _, x: out int _);
M(y: out var _, x: out var _);
M(y: out _, x: out _);
}
static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
}
[Fact]
public void OutVarDiscardInCtor_01()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out int i1);
new C(out int _);
new C(out var _);
new C(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CCCC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("int", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
}
[Fact]
public void OutVarDiscardInCtor_02()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out long x1);
new C(out long _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19),
// (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long _);
Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19),
// (7,19): error CS0165: Use of unassigned local variable 'x1'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl);
var discard1 = GetDiscardDesignations(tree).Single();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("long _", declaration1.ToString());
Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("long", declaration1.Type.ToString());
Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
}
[Fact]
public void OutVarDiscardAliasInfo_01()
{
var source =
@"
using alias1 = System.Int32;
using var = System.Int32;
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString());
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString());
}
[Fact]
public void OutVarDiscardAliasInfo_02()
{
var source =
@"
enum alias1 : long {}
class var {}
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int'
// new C(out alias1 _);
Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19),
// (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int'
// new C(out var _);
Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString());
Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind);
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
}
[Fact]
public void OutVarDiscardInCtorInitializer()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C ""); }
static void Main()
{
new Derived2(out int i2);
new Derived3(out int i3);
new Derived4();
}
}
public class Derived2 : C
{
public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); }
}
public class Derived3 : C
{
public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); }
}
public class Derived4 : C
{
public Derived4(out int i) : base(out _) { i = 4; }
public Derived4() : this(out _) { System.Console.Write(""Derived4""); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4");
}
[Fact]
public void DiscardNotRecognizedInOtherScenarios()
{
var source =
@"
public class C
{
void M<T>()
{
_.ToString();
M(_);
_<T>.ToString();
(_<T>, _<T>) = (1, 2);
M<_>();
new C() { _ = 1 };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,9): error CS0103: The name '_' does not exist in the current context
// _.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9),
// (7,11): error CS0103: The name '_' does not exist in the current context
// M(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11),
// (8,9): error CS0103: The name '_' does not exist in the current context
// _<T>.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9),
// (9,10): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10),
// (9,16): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16),
// (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// M<_>();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11),
// (11,19): error CS0117: 'C' does not contain a definition for '_'
// new C() { _ = 1 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19)
);
}
[Fact]
public void TypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
System.Console.Write(t.GetType().ToString());
}
static void Main()
{
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "System.Int32");
}
[Fact]
public void UntypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
}
static void Main()
{
M(out var _);
M(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out var _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9),
// (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9)
);
}
[Fact]
public void PickOverloadWithTypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); }
static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); }
static void Main()
{
M(out object _);
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "object returning M. int returning M.");
}
[Fact]
public void CannotPickOverloadWithUntypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; }
static void M(out int x) { x = 2; }
static void Main()
{
M(out var _);
M(out _);
M(out byte _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out var _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9),
// (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9),
// (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object'
// M(out byte _);
Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15)
);
}
[Fact]
public void NoOverloadWithDiscard()
{
var source =
@"
public class A { }
public class B : A
{
static void M(A a)
{
a.M2(out A x);
a.M2(out A _);
}
}
public static class S
{
public static void M2(this A self, out B x) { x = null; }
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore });
comp.VerifyDiagnostics(
// (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A x);
Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18),
// (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A _);
Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18)
);
}
[Fact]
[WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")]
public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier()
{
var source =
@"
public class C
{
static void M(string x)
{
if(true)
&& int.TryParse(x, out int y)) id(iVal);
// Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single();
Assert.Equal("x", x.ToString());
Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString());
}
[Fact]
public void DuplicateDeclarationInSwitchBlock()
{
var text = @"
public class C
{
public static void Main(string[] args)
{
switch (args.Length)
{
case 0:
M(M(out var x1), x1);
M(M(out int x1), x1);
break;
case 1:
M(M(out int x1), x1);
break;
}
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}";
var comp = CreateCompilationWithMscorlib45(text);
comp.VerifyDiagnostics(
// (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29),
// (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29),
// (13,34): error CS0165: Use of unassigned local variable 'x1'
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x6Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x6Decl.Length);
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]);
}
[Fact]
public void DeclarationInLocalFunctionParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(int a, int b) => a+b == 0;
}
";
// the scope of an expression variable introduced in the default expression
// of a local function parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,75): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30),
// (6,61): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61),
// (7,75): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30),
// (7,61): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInAnonymousMethodParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
System.Action<bool, int> d1 = delegate (
bool b = M(M(out int z1), z1),
int s2 = z1)
{ var t = z1; };
System.Action<bool, int> d2 = delegate (
bool b = M(M(out var z2), z2),
int s2 = z2)
{ var t = z2; };
int x = z1 + z2;
d1 = d2 = null;
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}
";
// the scope of an expression variable introduced in the default expression
// of a lambda parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify(
// (9,55): error CS0103: The name 'z1' does not exist in the current context
// { var t = z1; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55),
// (13,55): error CS0103: The name 'z2' does not exist in the current context
// { var t = z2; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55),
// (15,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17),
// (15,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First();
Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString());
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void Scope_LocalFunction_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_05()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_LocalFunction_Attribute_06()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_InvalidArrayDimensions01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
int[Test1(out int x1), x1] _1;
int[Test1(out int x2), x2] x2;
}
static int Test1(out int x)
{
x = 1;
return 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12),
// (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27),
// (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12),
// (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13),
// (7,27): warning CS0168: The variable 'x1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27),
// (7,36): warning CS0168: The variable '_1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36),
// (8,27): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27),
// (8,36): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyNotAnOutLocal(model, x1Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref);
}
[Fact]
public void Scope_InvalidArrayDimensions_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using (int[] d = null)
{
Dummy(x1);
}
}
void Test2()
{
using (int[] d = null)
Dummy(x2);
}
void Test3()
{
var x3 = 11;
Dummy(x3);
using (int[] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 3; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16),
// file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19),
// file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// file.cs(14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16),
// file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19),
// file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51),
// file.cs(21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16),
// file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19),
// file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51),
// file.cs(30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using int[TakeOutParam(true, out var x1), x1] d = null;
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
using int[TakeOutParam(true, out var x2), x2] d = null;
Dummy(x2);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9),
// (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18),
// (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19),
// (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// (13,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15),
// (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9),
// (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18),
// (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19),
// (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46),
// (21,46): warning CS0168: The variable 'x2' is declared but never used
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyNotAnOutLocal(model, x2Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true);
}
[Fact]
public void Scope_InvalidArrayDimensions_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(object x) {return true;}
void Test1()
{
for (int[] a = null;;)
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
for (int[] a = null;;)
Dummy(x2);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 2; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17),
// file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18),
// file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49),
// file.cs(13,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19),
// file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53),
// file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17),
// file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45),
// file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18),
// file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49),
// file.cs(22,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19),
// file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
unsafe void Test1()
{
fixed (int[TakeOutParam(true, out var x1), x1] d = null)
{
Dummy(x1);
}
}
unsafe void Test2()
{
fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Dummy(x2);
}
unsafe void Test3()
{
var x3 = 11;
Dummy(x3);
fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test1()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17),
// (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19),
// (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52),
// (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56),
// (14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test2()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17),
// (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19),
// (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52),
// (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56),
// (21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test3()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17),
// (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19),
// (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52),
// (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56),
// (30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void DeclarationInNameof_00()
{
var text = @"
class C
{
public static void Main()
{
var x = nameof(M2(M1(out var x1), x1)).ToString();
}
static int M1(out int z) => z = 1;
static int M2(int a, int b) => 2;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,24): error CS8081: Expression does not have a name.
// var x = nameof(M2(M1(out var x1), x1)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "x1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(1, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
public void DeclarationInNameof_01()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(object a, int b) => b == 0;
}
";
// the scope of an expression variable introduced in the default expression
// of a local function parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,83): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83),
// (6,39): error CS8081: Expression does not have a name.
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30),
// (6,69): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69),
// (7,83): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83),
// (7,39): error CS8081: Expression does not have a name.
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30),
// (7,69): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02a()
{
var text = @"
[My(C.M(nameof(C.M(out int z1)), z1), z1)]
[My(C.M(nameof(C.M(out var z2)), z2), z2)]
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (2,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16),
// (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5),
// (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39),
// (3,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16),
// (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5),
// (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02b()
{
var text1 = @"
[assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
[assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
";
var text2 = @"
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 });
compilation.VerifyDiagnostics(
// (2,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26),
// (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15),
// (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49),
// (3,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26),
// (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15),
// (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_03()
{
var text = @"
class C
{
public static void Main(string[] args)
{
switch ((object)args.Length)
{
case !M(nameof(M(out int z1)), z1):
System.Console.WriteLine(z1);
break;
case !M(nameof(M(out var z2)), z2):
System.Console.WriteLine(z2);
break;
}
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (8,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28),
// (8,18): error CS0150: A constant value is expected
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18),
// (11,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28),
// (11,18): error CS0150: A constant value is expected
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18),
// (8,44): error CS0165: Use of unassigned local variable 'z1'
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44),
// (11,44): error CS0165: Use of unassigned local variable 'z2'
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_04()
{
var text = @"
class C
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
const bool c = (z1 + z2) == 0;
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (5,29): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29),
// (5,20): error CS0133: The expression being assigned to 'C.b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20),
// (6,21): error CS0103: The name 'z1' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21),
// (6,26): error CS0103: The name 'z2' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26),
// (4,29): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29),
// (4,20): error CS0133: The expression being assigned to 'C.a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_05()
{
var text = @"
class C
{
public static void Main(string[] args)
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
bool c = (z1 + z2) == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,33): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33),
// (6,24): error CS0133: The expression being assigned to 'a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24),
// (7,33): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33),
// (7,24): error CS0133: The expression being assigned to 'b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24),
// (6,49): error CS0165: Use of unassigned local variable 'z1'
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49),
// (7,49): error CS0165: Use of unassigned local variable 'z2'
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_06()
{
var text = @"
class C
{
public static void Main(string[] args)
{
string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
bool c = z1 == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27),
// (7,18): error CS0103: The name 'z1' does not exist in the current context
// bool c = z1 == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "z1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVar(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_01()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p =>
{
weakRef.TryGetTarget(out var x);
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_02()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_03()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
void Local1 (Action<T> onNext = p3 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_04()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_05()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y
select (Action<T>)( p =>
{
void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
)
)
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_06()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[p =>
{
weakRef.TryGetTarget(out var x);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_07()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_08()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
System.Type t3 = typeof(int[p3 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_09()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_10()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[from p in y
select (Action<T>)( p =>
{
System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
)
]
);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")]
public void GetEnclosingBinderInternalRecovery_11()
{
var text = @"
class Program
{
static void Main(string[] args)
{
foreach
other(some().F(a => TestOutVar(out var x) ? x : 1));
}
static void TestOutVar(out int a)
{
a = 0;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (6,16): error CS1003: Syntax error, '(' expected
// foreach
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16),
// (7,60): error CS1515: 'in' expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60),
// (7,60): error CS0230: Type and identifier are both required in a foreach statement
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60),
// (7,60): error CS1525: Invalid expression term ';'
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60),
// (7,60): error CS1026: ) expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var xDecl = GetOutVarDeclaration(tree, "x");
var xRef = GetReferences(tree, "x", 1);
VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates()
{
var source =
@"using System;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Func<int, bool> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (6,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Expression()
{
var source =
@"using System;
using System.Linq.Expressions;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Expression<Func<int, bool>> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (7,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Query()
{
var source =
@"using System.Linq;
class C
{
static void M()
{
var c = from x in new[] { 1, 2, 3 }
group x > 1 && F(out var y) && y == null
by x;
}
static bool F(out object o)
{
o = null;
return true;
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")]
public void SpeculativeSemanticModelWithOutDiscard()
{
var source =
@"class C
{
static void F()
{
C.G(out _);
}
static void G(out object o)
{
o = null;
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var identifierBefore = GetReferences(tree, "G").Single();
Assert.Equal(tree, identifierBefore.Location.SourceTree);
var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First();
var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);");
bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model);
Assert.True(success);
var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G");
Assert.Null(identifierAfter.Location.SourceTree);
var info = model.GetSymbolInfo(identifierAfter);
Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")]
[WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")]
public void GetForEachSymbolInfoWithOutVar()
{
var source =
@"using System.Collections.Generic;
public class C
{
void M()
{
foreach (var x in M2(out int i)) { }
}
IEnumerable<object> M2(out int j)
{
throw null;
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single();
var info = model.GetForEachStatementInfo(foreachStatement);
Assert.Equal("System.Object", info.ElementType.ToTestDisplayString());
Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()",
info.GetEnumeratorMethod.ToTestDisplayString());
}
[WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")]
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void DiscardAndArgList()
{
var text = @"
using System;
public class C
{
static void Main()
{
M(out _, __arglist(2, 3, true));
}
static void M(out int x, __arglist)
{
x = 0;
DumpArgs(new ArgIterator(__arglist));
}
static void DumpArgs(ArgIterator args)
{
while(args.GetRemainingCount() > 0)
{
TypedReference tr = args.GetNextArg();
object arg = TypedReference.ToObject(tr);
Console.Write(arg);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "23True");
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_01()
{
var text = @"
public class C
{
static void Main()
{
M(1, __arglist(out int y));
M(2, __arglist(out var z));
System.Console.WriteLine(z);
}
static void M(int x, __arglist)
{
x = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(1, __arglist(out int y));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28),
// (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32),
// (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_02()
{
var text = @"
public class C
{
static void Main()
{
__arglist(out int y);
__arglist(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23),
// (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9),
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27),
// (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23),
// (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_01()
{
var text = @"
public class C
{
static void M<T>() where T : new()
{
var x = new T(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z)", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)')
Children(1):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_02()
{
var text = @"
public class C
{
static void M<T>() where T : C, new()
{
var x = new T(out var z) {F1 = 1};
System.Console.WriteLine(z);
}
public int F1;
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z) {F1 = 1};
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z) {F1 = 1}", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}')
Children(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1')
Left:
IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
");
}
[Fact]
public void EventInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
static System.Func<bool> GetDelegate(bool value) => () => value;
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConstructorBodyOperation()
{
var text = @"
public class C
{
C() : this(out var x)
{ M(out var y); }
=> M(out var z);
C (out int x){x=1;}
void M (out int x){x=1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(out var x)", initializerSyntax.ToString());
compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree:
@"
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation initializerOperation = model.GetOperation(initializerSyntax);
Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind);
Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent);
Assert.Null(blockBodyOperation.Parent.Parent);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent);
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);')
Locals: Local_1: System.Int32 x
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Expression:
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void MethodBodyOperation()
{
var text = @"
public class C
{
int P
{
get {return M(out var x);} => M(out var y);
} => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax);
Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind);
Assert.Null(expressionBodyOperation.Parent.Parent);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent);
var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1);
Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString());
Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single();
Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);')
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyExpressionBodyOperation()
{
var text = @"
public class C
{
int P => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", node3.ToString());
compilation.VerifyOperationTree(node3, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Null(model.GetOperation(node3).Parent);
}
[Fact]
public void OutVarInConstructorUsedInObjectInitializer()
{
var source =
@"
public class C
{
public int Number { get; set; }
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { Number = i };
System.Console.WriteLine(c.Number);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
public void OutVarInConstructorUsedInCollectionInitializer()
{
var source =
@"
public class C : System.Collections.Generic.List<int>
{
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { i, i, i };
System.Console.WriteLine(c[0]);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
[WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")]
public void Issue49997()
{
var text = @"
public class Cls
{
public static void Main()
{
if ()
.Test1().Test2(out var x1).Test3();
}
}
static class Ext
{
public static void Test3(this Cls x) {}
}
";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last();
Assert.True(model.GetSymbolInfo(node).IsEmpty);
}
}
internal static class OutVarTestsExtensions
{
internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self)
{
return (SingleVariableDesignationSyntax)self.Designation;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
namespace Roslyn.Utilities
{
internal static class AsyncLazy
{
public static AsyncLazy<T> Create<T>(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult)
=> new(asynchronousComputeFunction, cacheResult);
}
/// <summary>
/// Represents a value that can be retrieved synchronously or asynchronously by many clients.
/// The value will be computed on-demand the moment the first client asks for it. While being
/// computed, more clients can request the value. As long as there are outstanding clients the
/// underlying computation will proceed. If all outstanding clients cancel their request then
/// the underlying value computation will be cancelled as well.
///
/// Creators of an <see cref="AsyncLazy{T}" /> can specify whether the result of the computation is
/// cached for future requests or not. Choosing to not cache means the computation functions are kept
/// alive, whereas caching means the value (but not functions) are kept alive once complete.
/// </summary>
internal sealed class AsyncLazy<T> : ValueSource<T>
{
/// <summary>
/// The underlying function that starts an asynchronous computation of the resulting value.
/// Null'ed out once we've computed the result and we've been asked to cache it. Otherwise,
/// it is kept around in case the value needs to be computed again.
/// </summary>
private Func<CancellationToken, Task<T>>? _asynchronousComputeFunction;
/// <summary>
/// The underlying function that starts a synchronous computation of the resulting value.
/// Null'ed out once we've computed the result and we've been asked to cache it, or if we
/// didn't get any synchronous function given to us in the first place.
/// </summary>
private Func<CancellationToken, T>? _synchronousComputeFunction;
/// <summary>
/// Whether or not we should keep the value around once we've computed it.
/// </summary>
private readonly bool _cacheResult;
/// <summary>
/// The Task that holds the cached result.
/// </summary>
private Task<T>? _cachedResult;
/// <summary>
/// Mutex used to protect reading and writing to all mutable objects and fields. Traces
/// indicate that there's negligible contention on this lock, hence we can save some memory
/// by using a single lock for all AsyncLazy instances. Only trivial and non-reentrant work
/// should be done while holding the lock.
/// </summary>
private static readonly NonReentrantLock s_gate = new(useThisInstanceForSynchronization: true);
/// <summary>
/// The hash set of all currently outstanding asynchronous requests. Null if there are no requests,
/// and will never be empty.
/// </summary>
private HashSet<Request>? _requests;
/// <summary>
/// If an asynchronous request is active, the CancellationTokenSource that allows for
/// cancelling the underlying computation.
/// </summary>
private CancellationTokenSource? _asynchronousComputationCancellationSource;
/// <summary>
/// Whether a computation is active or queued on any thread, whether synchronous or
/// asynchronous.
/// </summary>
private bool _computationActive;
/// <summary>
/// Creates an AsyncLazy that always returns the value, analogous to <see cref="Task.FromResult{T}" />.
/// </summary>
public AsyncLazy(T value)
{
_cacheResult = true;
_cachedResult = Task.FromResult(value);
}
public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult)
: this(asynchronousComputeFunction, synchronousComputeFunction: null, cacheResult: cacheResult)
{
}
/// <summary>
/// Creates an AsyncLazy that supports both asynchronous computation and inline synchronous
/// computation.
/// </summary>
/// <param name="asynchronousComputeFunction">A function called to start the asynchronous
/// computation. This function should be cheap and non-blocking.</param>
/// <param name="synchronousComputeFunction">A function to do the work synchronously, which
/// is allowed to block. This function should not be implemented by a simple Wait on the
/// asynchronous value. If that's all you are doing, just don't pass a synchronous function
/// in the first place.</param>
/// <param name="cacheResult">Whether the result should be cached once the computation is
/// complete.</param>
public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, Func<CancellationToken, T>? synchronousComputeFunction, bool cacheResult)
{
Contract.ThrowIfNull(asynchronousComputeFunction);
_asynchronousComputeFunction = asynchronousComputeFunction;
_synchronousComputeFunction = synchronousComputeFunction;
_cacheResult = cacheResult;
}
#region Lock Wrapper for Invariant Checking
/// <summary>
/// Takes the lock for this object and if acquired validates the invariants of this class.
/// </summary>
private WaitThatValidatesInvariants TakeLock(CancellationToken cancellationToken)
{
s_gate.Wait(cancellationToken);
AssertInvariants_NoLock();
return new WaitThatValidatesInvariants(this);
}
private struct WaitThatValidatesInvariants : IDisposable
{
private readonly AsyncLazy<T> _asyncLazy;
public WaitThatValidatesInvariants(AsyncLazy<T> asyncLazy)
=> _asyncLazy = asyncLazy;
public void Dispose()
{
_asyncLazy.AssertInvariants_NoLock();
s_gate.Release();
}
}
private void AssertInvariants_NoLock()
{
// Invariant #1: thou shalt never have an asynchronous computation running without it
// being considered a computation
Contract.ThrowIfTrue(_asynchronousComputationCancellationSource != null &&
!_computationActive);
// Invariant #2: thou shalt never waste memory holding onto empty HashSets
Contract.ThrowIfTrue(_requests != null &&
_requests.Count == 0);
// Invariant #3: thou shalt never have an request if there is not
// something trying to compute it
Contract.ThrowIfTrue(_requests != null &&
!_computationActive);
// Invariant #4: thou shalt never have a cached value and any computation function
Contract.ThrowIfTrue(_cachedResult != null &&
(_synchronousComputeFunction != null || _asynchronousComputeFunction != null));
// Invariant #5: thou shalt never have a synchronous computation function but not an
// asynchronous one
Contract.ThrowIfTrue(_asynchronousComputeFunction == null && _synchronousComputeFunction != null);
}
#endregion
public override bool TryGetValue([MaybeNullWhen(false)] out T result)
{
// No need to lock here since this is only a fast check to
// see if the result is already computed.
if (_cachedResult != null)
{
result = _cachedResult.Result;
return true;
}
result = default;
return false;
}
public override T GetValue(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// If the value is already available, return it immediately
if (TryGetValue(out var value))
{
return value;
}
Request? request = null;
AsynchronousComputationToStart? newAsynchronousComputation = null;
using (TakeLock(cancellationToken))
{
// If cached, get immediately
if (_cachedResult != null)
{
return _cachedResult.Result;
}
// If there is an existing computation active, we'll just create another request
if (_computationActive)
{
request = CreateNewRequest_NoLock();
}
else if (_synchronousComputeFunction == null)
{
// A synchronous request, but we have no synchronous function. Start off the async work
request = CreateNewRequest_NoLock();
newAsynchronousComputation = RegisterAsynchronousComputation_NoLock();
}
else
{
// We will do the computation here
_computationActive = true;
}
}
// If we simply created a new asynchronous request, so wait for it. Yes, we're blocking the thread
// but we don't want multiple threads attempting to compute the same thing.
if (request != null)
{
request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken);
// Since we already registered for cancellation, it's possible that the registration has
// cancelled this new computation if we were the only requester.
if (newAsynchronousComputation != null)
{
StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken);
}
// The reason we have synchronous codepaths in AsyncLazy is to support the synchronous requests for syntax trees
// that we may get from the compiler. Thus, it's entirely possible that this will be requested by the compiler or
// an analyzer on the background thread when another part of the IDE is requesting the same tree asynchronously.
// In that case we block the synchronous request on the asynchronous request, since that's better than alternatives.
return request.Task.WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
else
{
Contract.ThrowIfNull(_synchronousComputeFunction);
T result;
// We are the active computation, so let's go ahead and compute.
try
{
result = _synchronousComputeFunction(cancellationToken);
}
catch (OperationCanceledException)
{
// This cancelled for some reason. We don't care why, but
// it means anybody else waiting for this result isn't going to get it
// from us.
using (TakeLock(CancellationToken.None))
{
_computationActive = false;
if (_requests != null)
{
// There's a possible improvement here: there might be another synchronous caller who
// also wants the value. We might consider stealing their thread rather than punting
// to the thread pool.
newAsynchronousComputation = RegisterAsynchronousComputation_NoLock();
}
}
if (newAsynchronousComputation != null)
{
StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: null, callerCancellationToken: cancellationToken);
}
throw;
}
catch (Exception ex)
{
// We faulted for some unknown reason. We should simply fault everything.
CompleteWithTask(Task.FromException<T>(ex), CancellationToken.None);
throw;
}
// We have a value, so complete
CompleteWithTask(Task.FromResult(result), CancellationToken.None);
// Optimization: if they did cancel and the computation never observed it, let's throw so we don't keep
// processing a value somebody never wanted
cancellationToken.ThrowIfCancellationRequested();
return result;
}
}
private Request CreateNewRequest_NoLock()
{
if (_requests == null)
{
_requests = new HashSet<Request>();
}
var request = new Request();
_requests.Add(request);
return request;
}
public override Task<T> GetValueAsync(CancellationToken cancellationToken)
{
// Optimization: if we're already cancelled, do not pass go
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<T>(cancellationToken);
}
// Avoid taking the lock if a cached value is available
var cachedResult = _cachedResult;
if (cachedResult != null)
{
return cachedResult;
}
Request request;
AsynchronousComputationToStart? newAsynchronousComputation = null;
using (TakeLock(cancellationToken))
{
// If cached, get immediately
if (_cachedResult != null)
{
return _cachedResult;
}
request = CreateNewRequest_NoLock();
// If we have either synchronous or asynchronous work current in flight, we don't need to do anything.
// Otherwise, we shall start an asynchronous computation for this
if (!_computationActive)
{
newAsynchronousComputation = RegisterAsynchronousComputation_NoLock();
}
}
// We now have the request counted for, register for cancellation. It is critical this is
// done outside the lock, as our registration may immediately fire and we want to avoid the
// reentrancy
request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken);
if (newAsynchronousComputation != null)
{
StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken);
}
return request.Task;
}
private AsynchronousComputationToStart RegisterAsynchronousComputation_NoLock()
{
Contract.ThrowIfTrue(_computationActive);
Contract.ThrowIfNull(_asynchronousComputeFunction);
_asynchronousComputationCancellationSource = new CancellationTokenSource();
_computationActive = true;
return new AsynchronousComputationToStart(_asynchronousComputeFunction, _asynchronousComputationCancellationSource);
}
private struct AsynchronousComputationToStart
{
public readonly Func<CancellationToken, Task<T>> AsynchronousComputeFunction;
public readonly CancellationTokenSource CancellationTokenSource;
public AsynchronousComputationToStart(Func<CancellationToken, Task<T>> asynchronousComputeFunction, CancellationTokenSource cancellationTokenSource)
{
AsynchronousComputeFunction = asynchronousComputeFunction;
CancellationTokenSource = cancellationTokenSource;
}
}
private void StartAsynchronousComputation(AsynchronousComputationToStart computationToStart, Request? requestToCompleteSynchronously, CancellationToken callerCancellationToken)
{
var cancellationToken = computationToStart.CancellationTokenSource.Token;
// DO NOT ACCESS ANY FIELDS OR STATE BEYOND THIS POINT. Since this function
// runs unsynchronized, it's possible that during this function this request
// might be cancelled, and then a whole additional request might start and
// complete inline, and cache the result. By grabbing state before we check
// the cancellation token, we can be assured that we are only operating on
// a state that was complete.
try
{
cancellationToken.ThrowIfCancellationRequested();
var task = computationToStart.AsynchronousComputeFunction(cancellationToken);
// As an optimization, if the task is already completed, mark the
// request as being completed as well.
//
// Note: we want to do this before we do the .ContinueWith below. That way,
// when the async call to CompleteWithTask runs, it sees that we've already
// completed and can bail immediately.
if (requestToCompleteSynchronously != null && task.IsCompleted)
{
using (TakeLock(CancellationToken.None))
{
task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task);
}
requestToCompleteSynchronously.CompleteFromTask(task);
}
// We avoid creating a full closure just to pass the token along
// Also, use TaskContinuationOptions.ExecuteSynchronously so that we inline
// the continuation if asynchronousComputeFunction completes synchronously
task.ContinueWith(
(t, s) => CompleteWithTask(t, ((CancellationTokenSource)s!).Token),
computationToStart.CancellationTokenSource,
cancellationToken,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken)
{
// The underlying computation cancelled with the correct token, but we must ourselves ensure that the caller
// on our stack gets an OperationCanceledException thrown with the right token
callerCancellationToken.ThrowIfCancellationRequested();
// We can only be here if the computation was cancelled, which means all requests for the value
// must have been cancelled. Therefore, the ThrowIfCancellationRequested above must have thrown
// because that token from the requester was cancelled.
throw ExceptionUtilities.Unreachable;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void CompleteWithTask(Task<T> task, CancellationToken cancellationToken)
{
IEnumerable<Request> requestsToComplete;
using (TakeLock(cancellationToken))
{
// If the underlying computation was cancelled, then all state was already updated in OnAsynchronousRequestCancelled
// and there is no new work to do here. We *must* use the local one since this completion may be running far after
// the background computation was cancelled and a new one might have already been enqueued. We must do this
// check here under the lock to ensure proper synchronization with OnAsynchronousRequestCancelled.
cancellationToken.ThrowIfCancellationRequested();
// The computation is complete, so get all requests to complete and null out the list. We'll create another one
// later if it's needed
requestsToComplete = _requests ?? (IEnumerable<Request>)Array.Empty<Request>();
_requests = null;
// The computations are done
_asynchronousComputationCancellationSource = null;
_computationActive = false;
task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task);
}
// Complete the requests outside the lock. It's not necessary to do this (none of this is touching any shared state)
// but there's no reason to hold the lock so we could reduce any theoretical lock contention.
foreach (var requestToComplete in requestsToComplete)
{
requestToComplete.CompleteFromTask(task);
}
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
private Task<T> GetCachedValueAndCacheThisValueIfNoneCached_NoLock(Task<T> task)
{
if (_cachedResult != null)
{
return _cachedResult;
}
else
{
if (_cacheResult && task.Status == TaskStatus.RanToCompletion)
{
// Hold onto the completed task. We can get rid of the computation functions for good
_cachedResult = task;
_asynchronousComputeFunction = null;
_synchronousComputeFunction = null;
}
return task;
}
}
private void OnAsynchronousRequestCancelled(object? state)
{
var request = (Request)state!;
CancellationTokenSource? cancellationTokenSource = null;
using (TakeLock(CancellationToken.None))
{
// Now try to remove it. It's possible that requests may already be null. You could
// imagine that cancellation was requested, but before we could acquire the lock
// here the computation completed and the entire CompleteWithTask synchronized
// block ran. In that case, the requests collection may already be null, or it
// (even scarier!) may have been replaced with another collection because another
// computation has started.
if (_requests != null)
{
if (_requests.Remove(request))
{
if (_requests.Count == 0)
{
_requests = null;
if (_asynchronousComputationCancellationSource != null)
{
cancellationTokenSource = _asynchronousComputationCancellationSource;
_asynchronousComputationCancellationSource = null;
_computationActive = false;
}
}
}
}
}
request.Cancel();
cancellationTokenSource?.Cancel();
}
/// <remarks>
/// This inherits from <see cref="TaskCompletionSource{TResult}"/> to avoid allocating two objects when we can just use one.
/// The public surface area of <see cref="TaskCompletionSource{TResult}"/> should probably be avoided in favor of the public
/// methods on this class for correct behavior.
/// </remarks>
private sealed class Request : TaskCompletionSource<T>
{
/// <summary>
/// The <see cref="CancellationToken"/> associated with this request. This field will be initialized before
/// any cancellation is observed from the token.
/// </summary>
private CancellationToken _cancellationToken;
private CancellationTokenRegistration _cancellationTokenRegistration;
// We want to always run continuations asynchronously. Running them synchronously could result in deadlocks:
// if we're looping through a bunch of Requests and completing them one by one, and the continuation for the
// first Request was then blocking waiting for a later Request, we would hang. It also could cause performance
// issues. If the first request then consumes a lot of CPU time, we're not letting other Requests complete that
// could use another CPU core at the same time.
public Request() : base(TaskCreationOptions.RunContinuationsAsynchronously)
{
}
public void RegisterForCancellation(Action<object?> callback, CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
_cancellationTokenRegistration = cancellationToken.Register(callback, this);
}
public void CompleteFromTask(Task<T> task)
{
// As an optimization, we'll cancel the request even we did get a value for it.
// That way things abort sooner.
if (task.IsCanceled || _cancellationToken.IsCancellationRequested)
{
Cancel();
}
else if (task.IsFaulted)
{
// TrySetException wraps its argument in an AggregateException, so we pass the inner exceptions from
// the antecedent to avoid wrapping in two layers of AggregateException.
RoslynDebug.AssertNotNull(task.Exception);
if (task.Exception.InnerExceptions.Count > 0)
this.TrySetException(task.Exception.InnerExceptions);
else
this.TrySetException(task.Exception);
}
else
{
this.TrySetResult(task.Result);
}
_cancellationTokenRegistration.Dispose();
}
public void Cancel()
=> this.TrySetCanceled(_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.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
namespace Roslyn.Utilities
{
internal static class AsyncLazy
{
public static AsyncLazy<T> Create<T>(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult)
=> new(asynchronousComputeFunction, cacheResult);
}
/// <summary>
/// Represents a value that can be retrieved synchronously or asynchronously by many clients.
/// The value will be computed on-demand the moment the first client asks for it. While being
/// computed, more clients can request the value. As long as there are outstanding clients the
/// underlying computation will proceed. If all outstanding clients cancel their request then
/// the underlying value computation will be cancelled as well.
///
/// Creators of an <see cref="AsyncLazy{T}" /> can specify whether the result of the computation is
/// cached for future requests or not. Choosing to not cache means the computation functions are kept
/// alive, whereas caching means the value (but not functions) are kept alive once complete.
/// </summary>
internal sealed class AsyncLazy<T> : ValueSource<T>
{
/// <summary>
/// The underlying function that starts an asynchronous computation of the resulting value.
/// Null'ed out once we've computed the result and we've been asked to cache it. Otherwise,
/// it is kept around in case the value needs to be computed again.
/// </summary>
private Func<CancellationToken, Task<T>>? _asynchronousComputeFunction;
/// <summary>
/// The underlying function that starts a synchronous computation of the resulting value.
/// Null'ed out once we've computed the result and we've been asked to cache it, or if we
/// didn't get any synchronous function given to us in the first place.
/// </summary>
private Func<CancellationToken, T>? _synchronousComputeFunction;
/// <summary>
/// Whether or not we should keep the value around once we've computed it.
/// </summary>
private readonly bool _cacheResult;
/// <summary>
/// The Task that holds the cached result.
/// </summary>
private Task<T>? _cachedResult;
/// <summary>
/// Mutex used to protect reading and writing to all mutable objects and fields. Traces
/// indicate that there's negligible contention on this lock, hence we can save some memory
/// by using a single lock for all AsyncLazy instances. Only trivial and non-reentrant work
/// should be done while holding the lock.
/// </summary>
private static readonly NonReentrantLock s_gate = new(useThisInstanceForSynchronization: true);
/// <summary>
/// The hash set of all currently outstanding asynchronous requests. Null if there are no requests,
/// and will never be empty.
/// </summary>
private HashSet<Request>? _requests;
/// <summary>
/// If an asynchronous request is active, the CancellationTokenSource that allows for
/// cancelling the underlying computation.
/// </summary>
private CancellationTokenSource? _asynchronousComputationCancellationSource;
/// <summary>
/// Whether a computation is active or queued on any thread, whether synchronous or
/// asynchronous.
/// </summary>
private bool _computationActive;
/// <summary>
/// Creates an AsyncLazy that always returns the value, analogous to <see cref="Task.FromResult{T}" />.
/// </summary>
public AsyncLazy(T value)
{
_cacheResult = true;
_cachedResult = Task.FromResult(value);
}
public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult)
: this(asynchronousComputeFunction, synchronousComputeFunction: null, cacheResult: cacheResult)
{
}
/// <summary>
/// Creates an AsyncLazy that supports both asynchronous computation and inline synchronous
/// computation.
/// </summary>
/// <param name="asynchronousComputeFunction">A function called to start the asynchronous
/// computation. This function should be cheap and non-blocking.</param>
/// <param name="synchronousComputeFunction">A function to do the work synchronously, which
/// is allowed to block. This function should not be implemented by a simple Wait on the
/// asynchronous value. If that's all you are doing, just don't pass a synchronous function
/// in the first place.</param>
/// <param name="cacheResult">Whether the result should be cached once the computation is
/// complete.</param>
public AsyncLazy(Func<CancellationToken, Task<T>> asynchronousComputeFunction, Func<CancellationToken, T>? synchronousComputeFunction, bool cacheResult)
{
Contract.ThrowIfNull(asynchronousComputeFunction);
_asynchronousComputeFunction = asynchronousComputeFunction;
_synchronousComputeFunction = synchronousComputeFunction;
_cacheResult = cacheResult;
}
#region Lock Wrapper for Invariant Checking
/// <summary>
/// Takes the lock for this object and if acquired validates the invariants of this class.
/// </summary>
private WaitThatValidatesInvariants TakeLock(CancellationToken cancellationToken)
{
s_gate.Wait(cancellationToken);
AssertInvariants_NoLock();
return new WaitThatValidatesInvariants(this);
}
private struct WaitThatValidatesInvariants : IDisposable
{
private readonly AsyncLazy<T> _asyncLazy;
public WaitThatValidatesInvariants(AsyncLazy<T> asyncLazy)
=> _asyncLazy = asyncLazy;
public void Dispose()
{
_asyncLazy.AssertInvariants_NoLock();
s_gate.Release();
}
}
private void AssertInvariants_NoLock()
{
// Invariant #1: thou shalt never have an asynchronous computation running without it
// being considered a computation
Contract.ThrowIfTrue(_asynchronousComputationCancellationSource != null &&
!_computationActive);
// Invariant #2: thou shalt never waste memory holding onto empty HashSets
Contract.ThrowIfTrue(_requests != null &&
_requests.Count == 0);
// Invariant #3: thou shalt never have an request if there is not
// something trying to compute it
Contract.ThrowIfTrue(_requests != null &&
!_computationActive);
// Invariant #4: thou shalt never have a cached value and any computation function
Contract.ThrowIfTrue(_cachedResult != null &&
(_synchronousComputeFunction != null || _asynchronousComputeFunction != null));
// Invariant #5: thou shalt never have a synchronous computation function but not an
// asynchronous one
Contract.ThrowIfTrue(_asynchronousComputeFunction == null && _synchronousComputeFunction != null);
}
#endregion
public override bool TryGetValue([MaybeNullWhen(false)] out T result)
{
// No need to lock here since this is only a fast check to
// see if the result is already computed.
if (_cachedResult != null)
{
result = _cachedResult.Result;
return true;
}
result = default;
return false;
}
public override T GetValue(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// If the value is already available, return it immediately
if (TryGetValue(out var value))
{
return value;
}
Request? request = null;
AsynchronousComputationToStart? newAsynchronousComputation = null;
using (TakeLock(cancellationToken))
{
// If cached, get immediately
if (_cachedResult != null)
{
return _cachedResult.Result;
}
// If there is an existing computation active, we'll just create another request
if (_computationActive)
{
request = CreateNewRequest_NoLock();
}
else if (_synchronousComputeFunction == null)
{
// A synchronous request, but we have no synchronous function. Start off the async work
request = CreateNewRequest_NoLock();
newAsynchronousComputation = RegisterAsynchronousComputation_NoLock();
}
else
{
// We will do the computation here
_computationActive = true;
}
}
// If we simply created a new asynchronous request, so wait for it. Yes, we're blocking the thread
// but we don't want multiple threads attempting to compute the same thing.
if (request != null)
{
request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken);
// Since we already registered for cancellation, it's possible that the registration has
// cancelled this new computation if we were the only requester.
if (newAsynchronousComputation != null)
{
StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken);
}
// The reason we have synchronous codepaths in AsyncLazy is to support the synchronous requests for syntax trees
// that we may get from the compiler. Thus, it's entirely possible that this will be requested by the compiler or
// an analyzer on the background thread when another part of the IDE is requesting the same tree asynchronously.
// In that case we block the synchronous request on the asynchronous request, since that's better than alternatives.
return request.Task.WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
else
{
Contract.ThrowIfNull(_synchronousComputeFunction);
T result;
// We are the active computation, so let's go ahead and compute.
try
{
result = _synchronousComputeFunction(cancellationToken);
}
catch (OperationCanceledException)
{
// This cancelled for some reason. We don't care why, but
// it means anybody else waiting for this result isn't going to get it
// from us.
using (TakeLock(CancellationToken.None))
{
_computationActive = false;
if (_requests != null)
{
// There's a possible improvement here: there might be another synchronous caller who
// also wants the value. We might consider stealing their thread rather than punting
// to the thread pool.
newAsynchronousComputation = RegisterAsynchronousComputation_NoLock();
}
}
if (newAsynchronousComputation != null)
{
StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: null, callerCancellationToken: cancellationToken);
}
throw;
}
catch (Exception ex)
{
// We faulted for some unknown reason. We should simply fault everything.
CompleteWithTask(Task.FromException<T>(ex), CancellationToken.None);
throw;
}
// We have a value, so complete
CompleteWithTask(Task.FromResult(result), CancellationToken.None);
// Optimization: if they did cancel and the computation never observed it, let's throw so we don't keep
// processing a value somebody never wanted
cancellationToken.ThrowIfCancellationRequested();
return result;
}
}
private Request CreateNewRequest_NoLock()
{
if (_requests == null)
{
_requests = new HashSet<Request>();
}
var request = new Request();
_requests.Add(request);
return request;
}
public override Task<T> GetValueAsync(CancellationToken cancellationToken)
{
// Optimization: if we're already cancelled, do not pass go
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<T>(cancellationToken);
}
// Avoid taking the lock if a cached value is available
var cachedResult = _cachedResult;
if (cachedResult != null)
{
return cachedResult;
}
Request request;
AsynchronousComputationToStart? newAsynchronousComputation = null;
using (TakeLock(cancellationToken))
{
// If cached, get immediately
if (_cachedResult != null)
{
return _cachedResult;
}
request = CreateNewRequest_NoLock();
// If we have either synchronous or asynchronous work current in flight, we don't need to do anything.
// Otherwise, we shall start an asynchronous computation for this
if (!_computationActive)
{
newAsynchronousComputation = RegisterAsynchronousComputation_NoLock();
}
}
// We now have the request counted for, register for cancellation. It is critical this is
// done outside the lock, as our registration may immediately fire and we want to avoid the
// reentrancy
request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken);
if (newAsynchronousComputation != null)
{
StartAsynchronousComputation(newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken);
}
return request.Task;
}
private AsynchronousComputationToStart RegisterAsynchronousComputation_NoLock()
{
Contract.ThrowIfTrue(_computationActive);
Contract.ThrowIfNull(_asynchronousComputeFunction);
_asynchronousComputationCancellationSource = new CancellationTokenSource();
_computationActive = true;
return new AsynchronousComputationToStart(_asynchronousComputeFunction, _asynchronousComputationCancellationSource);
}
private struct AsynchronousComputationToStart
{
public readonly Func<CancellationToken, Task<T>> AsynchronousComputeFunction;
public readonly CancellationTokenSource CancellationTokenSource;
public AsynchronousComputationToStart(Func<CancellationToken, Task<T>> asynchronousComputeFunction, CancellationTokenSource cancellationTokenSource)
{
AsynchronousComputeFunction = asynchronousComputeFunction;
CancellationTokenSource = cancellationTokenSource;
}
}
private void StartAsynchronousComputation(AsynchronousComputationToStart computationToStart, Request? requestToCompleteSynchronously, CancellationToken callerCancellationToken)
{
var cancellationToken = computationToStart.CancellationTokenSource.Token;
// DO NOT ACCESS ANY FIELDS OR STATE BEYOND THIS POINT. Since this function
// runs unsynchronized, it's possible that during this function this request
// might be cancelled, and then a whole additional request might start and
// complete inline, and cache the result. By grabbing state before we check
// the cancellation token, we can be assured that we are only operating on
// a state that was complete.
try
{
cancellationToken.ThrowIfCancellationRequested();
var task = computationToStart.AsynchronousComputeFunction(cancellationToken);
// As an optimization, if the task is already completed, mark the
// request as being completed as well.
//
// Note: we want to do this before we do the .ContinueWith below. That way,
// when the async call to CompleteWithTask runs, it sees that we've already
// completed and can bail immediately.
if (requestToCompleteSynchronously != null && task.IsCompleted)
{
using (TakeLock(CancellationToken.None))
{
task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task);
}
requestToCompleteSynchronously.CompleteFromTask(task);
}
// We avoid creating a full closure just to pass the token along
// Also, use TaskContinuationOptions.ExecuteSynchronously so that we inline
// the continuation if asynchronousComputeFunction completes synchronously
task.ContinueWith(
(t, s) => CompleteWithTask(t, ((CancellationTokenSource)s!).Token),
computationToStart.CancellationTokenSource,
cancellationToken,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken)
{
// The underlying computation cancelled with the correct token, but we must ourselves ensure that the caller
// on our stack gets an OperationCanceledException thrown with the right token
callerCancellationToken.ThrowIfCancellationRequested();
// We can only be here if the computation was cancelled, which means all requests for the value
// must have been cancelled. Therefore, the ThrowIfCancellationRequested above must have thrown
// because that token from the requester was cancelled.
throw ExceptionUtilities.Unreachable;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void CompleteWithTask(Task<T> task, CancellationToken cancellationToken)
{
IEnumerable<Request> requestsToComplete;
using (TakeLock(cancellationToken))
{
// If the underlying computation was cancelled, then all state was already updated in OnAsynchronousRequestCancelled
// and there is no new work to do here. We *must* use the local one since this completion may be running far after
// the background computation was cancelled and a new one might have already been enqueued. We must do this
// check here under the lock to ensure proper synchronization with OnAsynchronousRequestCancelled.
cancellationToken.ThrowIfCancellationRequested();
// The computation is complete, so get all requests to complete and null out the list. We'll create another one
// later if it's needed
requestsToComplete = _requests ?? (IEnumerable<Request>)Array.Empty<Request>();
_requests = null;
// The computations are done
_asynchronousComputationCancellationSource = null;
_computationActive = false;
task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task);
}
// Complete the requests outside the lock. It's not necessary to do this (none of this is touching any shared state)
// but there's no reason to hold the lock so we could reduce any theoretical lock contention.
foreach (var requestToComplete in requestsToComplete)
{
requestToComplete.CompleteFromTask(task);
}
}
[SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
private Task<T> GetCachedValueAndCacheThisValueIfNoneCached_NoLock(Task<T> task)
{
if (_cachedResult != null)
{
return _cachedResult;
}
else
{
if (_cacheResult && task.Status == TaskStatus.RanToCompletion)
{
// Hold onto the completed task. We can get rid of the computation functions for good
_cachedResult = task;
_asynchronousComputeFunction = null;
_synchronousComputeFunction = null;
}
return task;
}
}
private void OnAsynchronousRequestCancelled(object? state)
{
var request = (Request)state!;
CancellationTokenSource? cancellationTokenSource = null;
using (TakeLock(CancellationToken.None))
{
// Now try to remove it. It's possible that requests may already be null. You could
// imagine that cancellation was requested, but before we could acquire the lock
// here the computation completed and the entire CompleteWithTask synchronized
// block ran. In that case, the requests collection may already be null, or it
// (even scarier!) may have been replaced with another collection because another
// computation has started.
if (_requests != null)
{
if (_requests.Remove(request))
{
if (_requests.Count == 0)
{
_requests = null;
if (_asynchronousComputationCancellationSource != null)
{
cancellationTokenSource = _asynchronousComputationCancellationSource;
_asynchronousComputationCancellationSource = null;
_computationActive = false;
}
}
}
}
}
request.Cancel();
cancellationTokenSource?.Cancel();
}
/// <remarks>
/// This inherits from <see cref="TaskCompletionSource{TResult}"/> to avoid allocating two objects when we can just use one.
/// The public surface area of <see cref="TaskCompletionSource{TResult}"/> should probably be avoided in favor of the public
/// methods on this class for correct behavior.
/// </remarks>
private sealed class Request : TaskCompletionSource<T>
{
/// <summary>
/// The <see cref="CancellationToken"/> associated with this request. This field will be initialized before
/// any cancellation is observed from the token.
/// </summary>
private CancellationToken _cancellationToken;
private CancellationTokenRegistration _cancellationTokenRegistration;
// We want to always run continuations asynchronously. Running them synchronously could result in deadlocks:
// if we're looping through a bunch of Requests and completing them one by one, and the continuation for the
// first Request was then blocking waiting for a later Request, we would hang. It also could cause performance
// issues. If the first request then consumes a lot of CPU time, we're not letting other Requests complete that
// could use another CPU core at the same time.
public Request() : base(TaskCreationOptions.RunContinuationsAsynchronously)
{
}
public void RegisterForCancellation(Action<object?> callback, CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
_cancellationTokenRegistration = cancellationToken.Register(callback, this);
}
public void CompleteFromTask(Task<T> task)
{
// As an optimization, we'll cancel the request even we did get a value for it.
// That way things abort sooner.
if (task.IsCanceled || _cancellationToken.IsCancellationRequested)
{
Cancel();
}
else if (task.IsFaulted)
{
// TrySetException wraps its argument in an AggregateException, so we pass the inner exceptions from
// the antecedent to avoid wrapping in two layers of AggregateException.
RoslynDebug.AssertNotNull(task.Exception);
if (task.Exception.InnerExceptions.Count > 0)
this.TrySetException(task.Exception.InnerExceptions);
else
this.TrySetException(task.Exception);
}
else
{
this.TrySetResult(task.Result);
}
_cancellationTokenRegistration.Dispose();
}
public void Cancel()
=> this.TrySetCanceled(_cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.FindUsages;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor.FindUsages
{
[Shared]
[ExportLanguageService(typeof(IFindUsagesService), LanguageNames.FSharp)]
internal class FSharpFindUsagesService : IFindUsagesService
{
private readonly IFSharpFindUsagesService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpFindUsagesService(IFSharpFindUsagesService service)
=> _service = service;
public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken)
=> _service.FindImplementationsAsync(document, position, new FSharpFindUsagesContext(context, cancellationToken));
public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken)
=> _service.FindReferencesAsync(document, position, new FSharpFindUsagesContext(context, 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.FindUsages;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor.FindUsages
{
[Shared]
[ExportLanguageService(typeof(IFindUsagesService), LanguageNames.FSharp)]
internal class FSharpFindUsagesService : IFindUsagesService
{
private readonly IFSharpFindUsagesService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpFindUsagesService(IFSharpFindUsagesService service)
=> _service = service;
public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken)
=> _service.FindImplementationsAsync(document, position, new FSharpFindUsagesContext(context, cancellationToken));
public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken)
=> _service.FindReferencesAsync(document, position, new FSharpFindUsagesContext(context, cancellationToken));
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/QuickInfo/CSharpDiagnosticAnalyzerQuickInfoProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.QuickInfo
{
[ExportQuickInfoProvider(QuickInfoProviderNames.DiagnosticAnalyzer, LanguageNames.CSharp), Shared]
// This provider needs to run before the semantic quick info provider, because of the SuppressMessage attribute handling
// If it runs after it, BuildQuickInfoAsync is not called. This is not covered by a test.
[ExtensionOrder(Before = QuickInfoProviderNames.Semantic)]
internal class CSharpDiagnosticAnalyzerQuickInfoProvider : CommonQuickInfoProvider
{
private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService;
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpDiagnosticAnalyzerQuickInfoProvider(IDiagnosticAnalyzerService diagnosticAnalyzerService)
{
_diagnosticAnalyzerService = diagnosticAnalyzerService;
}
protected override async Task<QuickInfoItem?> BuildQuickInfoAsync(
QuickInfoContext context,
SyntaxToken token)
{
var document = context.Document;
return GetQuickinfoForPragmaWarning(document, token) ??
(await GetQuickInfoForSuppressMessageAttributeAsync(document, token, context.CancellationToken).ConfigureAwait(false));
}
protected override Task<QuickInfoItem?> BuildQuickInfoAsync(
CommonQuickInfoContext context,
SyntaxToken token)
{
// TODO: This provider currently needs access to Document/Project to compute applicable analyzers
// and provide quick info, which is not available in CommonQuickInfoContext.
return Task.FromResult<QuickInfoItem?>(null);
}
private QuickInfoItem? GetQuickinfoForPragmaWarning(Document document, SyntaxToken token)
{
var errorCodeNode = token.Parent switch
{
PragmaWarningDirectiveTriviaSyntax directive
=> token.IsKind(SyntaxKind.EndOfDirectiveToken)
? directive.ErrorCodes.LastOrDefault()
: directive.ErrorCodes.FirstOrDefault(),
{ Parent: PragmaWarningDirectiveTriviaSyntax } node => node,
_ => null,
};
if (errorCodeNode is null)
{
return null;
}
// https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning
// warning-list: A comma-separated list of warning numbers. The "CS" prefix is optional.
// errorCodeNode is single error code from the comma separated list
var errorCode = errorCodeNode switch
{
// case CS0219 or SA0012:
IdentifierNameSyntax identifierName => identifierName.Identifier.ValueText,
// case 0219 or 219:
// Take the number and add the "CS" prefix.
LiteralExpressionSyntax { RawKind: (int)SyntaxKind.NumericLiteralExpression } literal
=> int.TryParse(literal.Token.ValueText, out var errorCodeNumber)
? $"CS{errorCodeNumber:0000}"
: literal.Token.ValueText,
_ => null,
};
if (errorCode is null)
{
return null;
}
return GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(document, errorCode, errorCodeNode.Span);
}
private async Task<QuickInfoItem?> GetQuickInfoForSuppressMessageAttributeAsync(
Document document,
SyntaxToken token,
CancellationToken cancellationToken)
{
// SuppressMessageAttribute docs
// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.suppressmessageattribute
var suppressMessageCheckIdArgument = token.GetAncestor<AttributeArgumentSyntax>() switch
{
AttributeArgumentSyntax
{
Parent: AttributeArgumentListSyntax
{
Arguments: var arguments,
Parent: AttributeSyntax
{
Name: var attributeName
}
}
} argument when
attributeName.IsSuppressMessageAttribute() &&
(argument.NameColon is null
? arguments.IndexOf(argument) == 1 // Positional argument "checkId"
: argument.NameColon.Name.Identifier.ValueText == "checkId") // Named argument "checkId"
=> argument,
_ => null,
};
if (suppressMessageCheckIdArgument != null)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var checkIdObject = semanticModel.GetConstantValue(suppressMessageCheckIdArgument.Expression, cancellationToken);
if (checkIdObject.HasValue && checkIdObject.Value is string checkId)
{
var errorCode = checkId.ExtractErrorCodeFromCheckId();
return GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(document, errorCode, suppressMessageCheckIdArgument.Span);
}
}
return null;
}
private QuickInfoItem? GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(Document document,
string errorCode, TextSpan location)
{
var infoCache = _diagnosticAnalyzerService.AnalyzerInfoCache;
var hostAnalyzers = document.Project.Solution.State.Analyzers;
var groupedDiagnostics = hostAnalyzers.GetDiagnosticDescriptorsPerReference(infoCache, document.Project).Values;
var supportedDiagnostics = groupedDiagnostics.SelectMany(d => d);
var diagnosticDescriptor = supportedDiagnostics.FirstOrDefault(d => d.Id == errorCode);
if (diagnosticDescriptor != null)
{
return CreateQuickInfo(location, diagnosticDescriptor);
}
return null;
}
private static QuickInfoItem CreateQuickInfo(TextSpan location, DiagnosticDescriptor descriptor,
params TextSpan[] relatedSpans)
{
var description =
descriptor.Title.ToStringOrNull() ??
descriptor.Description.ToStringOrNull() ??
descriptor.MessageFormat.ToStringOrNull() ??
descriptor.Id;
var idTag = !string.IsNullOrWhiteSpace(descriptor.HelpLinkUri)
? new TaggedText(TextTags.Text, descriptor.Id, TaggedTextStyle.None, descriptor.HelpLinkUri, descriptor.HelpLinkUri)
: new TaggedText(TextTags.Text, descriptor.Id);
return QuickInfoItem.Create(location, sections: new[]
{
QuickInfoSection.Create(QuickInfoSectionKinds.Description, new[]
{
idTag,
new TaggedText(TextTags.Punctuation, ":"),
new TaggedText(TextTags.Space, " "),
new TaggedText(TextTags.Text, description)
}.ToImmutableArray())
}.ToImmutableArray(), relatedSpans: relatedSpans.ToImmutableArray());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.QuickInfo
{
[ExportQuickInfoProvider(QuickInfoProviderNames.DiagnosticAnalyzer, LanguageNames.CSharp), Shared]
// This provider needs to run before the semantic quick info provider, because of the SuppressMessage attribute handling
// If it runs after it, BuildQuickInfoAsync is not called. This is not covered by a test.
[ExtensionOrder(Before = QuickInfoProviderNames.Semantic)]
internal class CSharpDiagnosticAnalyzerQuickInfoProvider : CommonQuickInfoProvider
{
private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService;
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpDiagnosticAnalyzerQuickInfoProvider(IDiagnosticAnalyzerService diagnosticAnalyzerService)
{
_diagnosticAnalyzerService = diagnosticAnalyzerService;
}
protected override async Task<QuickInfoItem?> BuildQuickInfoAsync(
QuickInfoContext context,
SyntaxToken token)
{
var document = context.Document;
return GetQuickinfoForPragmaWarning(document, token) ??
(await GetQuickInfoForSuppressMessageAttributeAsync(document, token, context.CancellationToken).ConfigureAwait(false));
}
protected override Task<QuickInfoItem?> BuildQuickInfoAsync(
CommonQuickInfoContext context,
SyntaxToken token)
{
// TODO: This provider currently needs access to Document/Project to compute applicable analyzers
// and provide quick info, which is not available in CommonQuickInfoContext.
return Task.FromResult<QuickInfoItem?>(null);
}
private QuickInfoItem? GetQuickinfoForPragmaWarning(Document document, SyntaxToken token)
{
var errorCodeNode = token.Parent switch
{
PragmaWarningDirectiveTriviaSyntax directive
=> token.IsKind(SyntaxKind.EndOfDirectiveToken)
? directive.ErrorCodes.LastOrDefault()
: directive.ErrorCodes.FirstOrDefault(),
{ Parent: PragmaWarningDirectiveTriviaSyntax } node => node,
_ => null,
};
if (errorCodeNode is null)
{
return null;
}
// https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning
// warning-list: A comma-separated list of warning numbers. The "CS" prefix is optional.
// errorCodeNode is single error code from the comma separated list
var errorCode = errorCodeNode switch
{
// case CS0219 or SA0012:
IdentifierNameSyntax identifierName => identifierName.Identifier.ValueText,
// case 0219 or 219:
// Take the number and add the "CS" prefix.
LiteralExpressionSyntax { RawKind: (int)SyntaxKind.NumericLiteralExpression } literal
=> int.TryParse(literal.Token.ValueText, out var errorCodeNumber)
? $"CS{errorCodeNumber:0000}"
: literal.Token.ValueText,
_ => null,
};
if (errorCode is null)
{
return null;
}
return GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(document, errorCode, errorCodeNode.Span);
}
private async Task<QuickInfoItem?> GetQuickInfoForSuppressMessageAttributeAsync(
Document document,
SyntaxToken token,
CancellationToken cancellationToken)
{
// SuppressMessageAttribute docs
// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.suppressmessageattribute
var suppressMessageCheckIdArgument = token.GetAncestor<AttributeArgumentSyntax>() switch
{
AttributeArgumentSyntax
{
Parent: AttributeArgumentListSyntax
{
Arguments: var arguments,
Parent: AttributeSyntax
{
Name: var attributeName
}
}
} argument when
attributeName.IsSuppressMessageAttribute() &&
(argument.NameColon is null
? arguments.IndexOf(argument) == 1 // Positional argument "checkId"
: argument.NameColon.Name.Identifier.ValueText == "checkId") // Named argument "checkId"
=> argument,
_ => null,
};
if (suppressMessageCheckIdArgument != null)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var checkIdObject = semanticModel.GetConstantValue(suppressMessageCheckIdArgument.Expression, cancellationToken);
if (checkIdObject.HasValue && checkIdObject.Value is string checkId)
{
var errorCode = checkId.ExtractErrorCodeFromCheckId();
return GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(document, errorCode, suppressMessageCheckIdArgument.Span);
}
}
return null;
}
private QuickInfoItem? GetQuickInfoFromSupportedDiagnosticsOfProjectAnalyzers(Document document,
string errorCode, TextSpan location)
{
var infoCache = _diagnosticAnalyzerService.AnalyzerInfoCache;
var hostAnalyzers = document.Project.Solution.State.Analyzers;
var groupedDiagnostics = hostAnalyzers.GetDiagnosticDescriptorsPerReference(infoCache, document.Project).Values;
var supportedDiagnostics = groupedDiagnostics.SelectMany(d => d);
var diagnosticDescriptor = supportedDiagnostics.FirstOrDefault(d => d.Id == errorCode);
if (diagnosticDescriptor != null)
{
return CreateQuickInfo(location, diagnosticDescriptor);
}
return null;
}
private static QuickInfoItem CreateQuickInfo(TextSpan location, DiagnosticDescriptor descriptor,
params TextSpan[] relatedSpans)
{
var description =
descriptor.Title.ToStringOrNull() ??
descriptor.Description.ToStringOrNull() ??
descriptor.MessageFormat.ToStringOrNull() ??
descriptor.Id;
var idTag = !string.IsNullOrWhiteSpace(descriptor.HelpLinkUri)
? new TaggedText(TextTags.Text, descriptor.Id, TaggedTextStyle.None, descriptor.HelpLinkUri, descriptor.HelpLinkUri)
: new TaggedText(TextTags.Text, descriptor.Id);
return QuickInfoItem.Create(location, sections: new[]
{
QuickInfoSection.Create(QuickInfoSectionKinds.Description, new[]
{
idTag,
new TaggedText(TextTags.Punctuation, ":"),
new TaggedText(TextTags.Space, " "),
new TaggedText(TextTags.Text, description)
}.ToImmutableArray())
}.ToImmutableArray(), relatedSpans: relatedSpans.ToImmutableArray());
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Core/Diagnostics/SuppressMessageAttributeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics
{
public abstract partial class SuppressMessageAttributeTests
{
#region Local Suppression
public static IEnumerable<string[]> QualifiedAttributeNames { get; } = new[] {
new[] { "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute" },
new[] { "System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute" },
};
public static IEnumerable<string[]> SimpleAttributeNames { get; } = new[] {
new[] { "SuppressMessage" },
new[] { "UnconditionalSuppressMessage" }
};
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnType(string attrName)
{
await VerifyCSharpAsync(@"
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
public class C1
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleLocalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""TypeDeclaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateLocalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnMember(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public void Goo() {}
public void Goo1() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Goo") },
Diagnostic("Declaration", "Goo1"));
}
#endregion
#region Global Suppression
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N2"),
Diagnostic("Declaration", "N3"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces_NamespaceAndDescendants(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""namespaceanddescendants"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
namespace N5
{
}
}
namespace N.N1.N6.N7
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypesAndNamespaces_NamespaceAndDescendants(string attrName)
{
var source = @"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1.N2"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N4"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C2"")]
namespace N
{
namespace N1
{
class C1
{
}
namespace N2.N3
{
class C2
{
}
class C3
{
class C4
{
}
}
}
}
}
namespace N4
{
namespace N5
{
class C5
{
}
}
class C6
{
}
}
namespace N.N1.N2.N7
{
class C7
{
}
}
";
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"),
Diagnostic("Declaration", "N1"));
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ef"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Egg"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ele`2"")]
public class E
{
}
public interface Ef
{
}
public struct Egg
{
}
public delegate void Ele<T1,T2>(T1 x, T2 y);
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNestedTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C.A1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C+A2"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C+A3"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C.A4"")]
public class C
{
public class A1 { }
public class A2 { }
public class A3 { }
public delegate void A4();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("A") },
Diagnostic("Declaration", "A1"),
Diagnostic("Declaration", "A3"),
Diagnostic("Declaration", "A4"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GlobalSuppressionOnBasicModule(string attrName)
{
await VerifyBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""M"")>
Module M
Class C
End Class
End Module
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnMembers(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M3`1()"")]
public class C
{
int M1;
public void M2() {}
public static void M3<T>() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") },
new[] { Diagnostic("Declaration", "M2") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnValueTupleMemberWithDocId(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""~M:C.M~System.Threading.Tasks.Task{System.ValueTuple{System.Boolean,ErrorCode}}"")]
enum ErrorCode {}
class C
{
Task<(bool status, ErrorCode errorCode)> M() => null;
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleGlobalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""TypeDeclaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("E"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateGlobalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
#endregion
#region Syntax Semantics
[Fact]
public async Task WarningOnCommentAnalyzerCSharp()
{
await VerifyCSharpAsync("// Comment\r\n /* Comment */",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// Comment"),
Diagnostic("Comment", "/* Comment */"));
}
[Fact]
public async Task WarningOnCommentAnalyzerBasic()
{
await VerifyBasicAsync("' Comment",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' Comment"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""C.Goo():System.Void"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before class"),
Diagnostic("Comment", "// after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Member"", Target:=""C.Goo():System.Void"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' before module attributes"),
Diagnostic("Comment", "' before class"),
Diagnostic("Comment", "' after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""namespace"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "class").WithLocation(7, 9),
Diagnostic("Token", "C").WithLocation(7, 15),
Diagnostic("Token", "{").WithLocation(7, 17),
Diagnostic("Token", "}").WithLocation(7, 18),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndChildDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""NamespaceAndDescendants"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""Namespace"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "Class").WithLocation(5, 9),
Diagnostic("Token", "C").WithLocation(5, 15),
Diagnostic("Token", "End").WithLocation(6, 9),
Diagnostic("Token", "Class").WithLocation(6, 13),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndDescendantsDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""NamespaceAndDescendants"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[InlineData("Namespace")]
[InlineData("NamespaceAndDescendants")]
public async Task DontSuppressSyntaxDiagnosticsInRootNamespaceBasic(string scope)
{
await VerifyBasicAsync($@"
<module: System.Diagnostics.SuppressMessage(""Test"", ""Comment"", Scope:=""{scope}"", Target:=""RootNamespace"")>
' In root namespace
",
rootNamespace: "RootNamespace",
analyzers: new[] { new WarningOnCommentAnalyzer() },
diagnostics: Diagnostic("Comment", "' In root namespace").WithLocation(3, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
namespace N
[|{
[" + attrName + @"(""Test"", ""Token"")]
class C<T> {}
[" + attrName + @"(""Test"", ""Token"")]
struct S<T> {}
[" + attrName + @"(""Test"", ""Token"")]
interface I<T>{}
[" + attrName + @"(""Test"", ""Token"")]
enum E {}
[" + attrName + @"(""Test"", ""Token"")]
delegate void D();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(20, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Namespace [|N
<" + attrName + @"(""Test"", ""Token"")>
Module M
End Module
<" + attrName + @"(""Test"", ""Token"")>
Class C
End Class
<" + attrName + @"(""Test"", ""Token"")>
Structure S
End Structure
<" + attrName + @"(""Test"", ""Token"")>
Interface I
End Interface
<" + attrName + @"(""Test"", ""Token"")>
Enum E
None
End Enum
<" + attrName + @"(""Test"", ""Token"")>
Delegate Sub D()
End|] Namespace
",
Diagnostic("Token", "N").WithLocation(4, 11),
Diagnostic("Token", "End").WithLocation(28, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int field1 = 1, field2 = 2;
[" + attrName + @"(""Test"", ""Token"")]
int field3 = 3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEnumFieldsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""E.Field1"")]
// before enum
public enum E
{
// before Field1 declaration
Field1, // after Field1 declaration
Field2 // after Field2 declaration
}
// after enum
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before enum"),
Diagnostic("Comment", "// after Field1 declaration"),
Diagnostic("Comment", "// after Field2 declaration"),
Diagnostic("Comment", "// after enum"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public field1 As Integer = 1,
field2 As Double = 2.0
<" + attrName + @"(""Test"", ""Token"")>
Public field3 As Integer = 3
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E1;
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E2, E3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Event E1 As System.Action(Of Integer)
<" + attrName + @"(""Test"", ""Token"")>
Public Event E2(ByVal arg As Integer)
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
[|{
[" + attrName + @"(""Test"", ""Token"")]
add {}
remove|] {}
}
}
",
Diagnostic("Token", "{").WithLocation(5, 5),
Diagnostic("Token", "remove").WithLocation(8, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer[|)
<" + attrName + @"(""Test"", ""Token"")>
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler|](value As Action(Of Integer))
End RemoveHandler
RaiseEvent(obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", ")"),
Diagnostic("Token", "RemoveHandler"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
{
add {[|}
[" + attrName + @"(""Test"", ""Token"")]
remove {}
}|]
}
",
Diagnostic("Token", "}").WithLocation(6, 14),
Diagnostic("Token", "}").WithLocation(9, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End [|AddHandler
<" + attrName + @"(""Test"", ""Token"")>
RemoveHandler(value As Action(Of Integer))
End RemoveHandler
RaiseEvent|](obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", "AddHandler"),
Diagnostic("Token", "RaiseEvent"));
}
[WorkItem(1103442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103442")]
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnRaiseEventAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler(value As Action(Of Integer))
End [|RemoveHandler
<" + attrName + @"(""Test"", ""Token"")>
RaiseEvent(obj As Integer)
End RaiseEvent
End|] Event
End Class
",
Diagnostic("Token", "RemoveHandler"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int Property1 { get; set; }
[" + attrName + @"(""Test"", ""Token"")]
int Property2
{
get { return 2; }
set { Property1 = 2; }
}
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(15, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Property Property1 As Integer
<" + attrName + @"(""Test"", ""Token"")>
Property Property2 As Integer
Get
Return 2
End Get
Set(value As Integer)
Property1 = value
End Set
End Property
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 7),
Diagnostic("Token", "End").WithLocation(17, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As [|Integer
<" + attrName + @"(""Test"", ""Token"")>
Get
Return 2
End Get
Set|](value As Integer)
x = value
End Set
End Property
End Class
",
Diagnostic("Token", "Integer").WithLocation(4, 28),
Diagnostic("Token", "Set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As Integer
Get
Return 2
End [|Get
<" + attrName + @"(""Test"", ""Token"")>
Set(value As Integer)
x = value
End Set
End|] Property
End Class
",
Diagnostic("Token", "Get").WithLocation(7, 13),
Diagnostic("Token", "End").WithLocation(12, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x[|;
[" + attrName + @"(""Test"", ""Token"")]
int this[int i]
{
get { return 2; }
set { x = 2; }
}
}|]
",
Diagnostic("Token", ";").WithLocation(4, 10),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerSetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
{
get { return 2; [|}
[" + attrName + @"(""Test"", ""Token"")]
set { x = 2; }
}|]
}
",
Diagnostic("Token", "}").WithLocation(7, 25),
Diagnostic("Token", "}").WithLocation(10, 5));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
abstract class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public void M1<T>() {}
[" + attrName + @"(""Test"", ""Token"")]
public abstract void M2();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Public MustInherit Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Function M2(Of T)() As Integer
Return 0
End Function
<" + attrName + @"(""Test"", ""Token"")>
Public MustOverride Sub M3()
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 26),
Diagnostic("Token", "End").WithLocation(12, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public static C operator +(C a, C b)
{
return null;
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Shared Operator +(ByVal a As C, ByVal b As C) As C
Return Nothing
End Operator
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(7, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class Base
{
public Base(int x) {}
}
class C : Base
[|{
[" + attrName + @"(""Test"", ""Token"")]
public C() : base(0) {}
}|]
",
Diagnostic("Token", "{").WithLocation(8, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Sub New()
End Sub
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnDestructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
~C() {}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
class D
{
class E
{
}
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Class D
Class E
End Class
End Class
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(8, 1));
}
#endregion
#region Special Cases
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageCompilationEnded(string attrName)
{
await VerifyCSharpAsync(
@"[module: " + attrName + @"(""Test"", ""CompilationEnded"")]",
new[] { new WarningOnCompilationEndedAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnPropertyAccessor(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public string P { get; private set; }
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("get_") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnDelegateInvoke(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
delegate void D();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Invoke") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyCSharp(string attrName)
{
await VerifyCSharpAsync(
@"
public class C
{
[" + attrName + @"(""Test"", ""CodeBody"")]
void Goo()
{
Goo();
}
}
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.CSharp) });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyBasic(string attrName)
{
await VerifyBasicAsync(
@"
Public Class C
<" + attrName + @"(""Test"", ""CodeBody"")>
Sub Goo()
Goo()
End Sub
End Class
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.VisualBasic) });
}
#endregion
#region Attribute Decoding
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task UnnecessaryScopeAndTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C1
{
}
[" + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
public class C2
{
}
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C"")]
public class C3
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""E"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MissingScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidAttributeConstructorParameters(string attrName)
{
await VerifyBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
<module: " + attrName + @"UndeclaredIdentifier, ""Comment"")>
<module: " + attrName + @"(""Test"", UndeclaredIdentifier)>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=UndeclaredIdentifier, Target:=""C"")>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Type"", Target:=UndeclaredIdentifier)>
Class C
End Class
",
new[] { new WarningOnTypeDeclarationAnalyzer() },
Diagnostic("TypeDeclaration", "C").WithLocation(9, 7));
}
#endregion
protected async Task VerifyCSharpAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.CSharp, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsCSharpAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.CSharp, diagnostics);
}
protected async Task VerifyBasicAsync(string source, string rootNamespace, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
Assert.False(string.IsNullOrWhiteSpace(rootNamespace), string.Format("Invalid root namespace '{0}'", rootNamespace));
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics, rootNamespace: rootNamespace);
}
protected async Task VerifyBasicAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsBasicAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.VisualBasic, diagnostics);
}
protected abstract Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null);
// Generate a diagnostic on every token in the specified spans, and verify that only the specified diagnostics are not suppressed
private Task VerifyTokenDiagnosticsAsync(string markup, string language, DiagnosticDescription[] diagnostics)
{
MarkupTestFile.GetSpans(markup, out var source, out ImmutableArray<TextSpan> spans);
Assert.True(spans.Length > 0, "Must specify a span within which to generate diagnostics on each token");
return VerifyAsync(source, language, new DiagnosticAnalyzer[] { new WarningOnTokenAnalyzer(spans) }, diagnostics);
}
protected abstract bool ConsiderArgumentsForComparingDiagnostics { get; }
protected DiagnosticDescription Diagnostic(string id, string squiggledText)
{
var arguments = this.ConsiderArgumentsForComparingDiagnostics && squiggledText != null
? new[] { squiggledText }
: null;
return new DiagnosticDescription(id, false, squiggledText, arguments, null, null, 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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics
{
public abstract partial class SuppressMessageAttributeTests
{
#region Local Suppression
public static IEnumerable<string[]> QualifiedAttributeNames { get; } = new[] {
new[] { "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute" },
new[] { "System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute" },
};
public static IEnumerable<string[]> SimpleAttributeNames { get; } = new[] {
new[] { "SuppressMessage" },
new[] { "UnconditionalSuppressMessage" }
};
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnType(string attrName)
{
await VerifyCSharpAsync(@"
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
public class C1
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleLocalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""TypeDeclaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateLocalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"")]
[" + attrName + @"(""Test"", ""Declaration"")]
public class C
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task LocalSuppressionOnMember(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public void Goo() {}
public void Goo1() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Goo") },
Diagnostic("Declaration", "Goo1"));
}
#endregion
#region Global Suppression
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N2"),
Diagnostic("Declaration", "N3"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNamespaces_NamespaceAndDescendants(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""namespaceanddescendants"", Target=""N4"")]
namespace N
{
namespace N1
{
namespace N2.N3
{
}
}
}
namespace N4
{
namespace N5
{
}
}
namespace N.N1.N6.N7
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypesAndNamespaces_NamespaceAndDescendants(string attrName)
{
var source = @"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1.N2"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N4"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C2"")]
namespace N
{
namespace N1
{
class C1
{
}
namespace N2.N3
{
class C2
{
}
class C3
{
class C4
{
}
}
}
}
}
namespace N4
{
namespace N5
{
class C5
{
}
}
class C6
{
}
}
namespace N.N1.N2.N7
{
class C7
{
}
}
";
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") },
Diagnostic("Declaration", "N"),
Diagnostic("Declaration", "N1"));
await VerifyCSharpAsync(source,
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C1"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ef"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Egg"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ele`2"")]
public class E
{
}
public interface Ef
{
}
public struct Egg
{
}
public delegate void Ele<T1,T2>(T1 x, T2 y);
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnNestedTypes(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C.A1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C+A2"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C+A3"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C.A4"")]
public class C
{
public class A1 { }
public class A2 { }
public class A3 { }
public delegate void A4();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("A") },
Diagnostic("Declaration", "A1"),
Diagnostic("Declaration", "A3"),
Diagnostic("Declaration", "A4"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GlobalSuppressionOnBasicModule(string attrName)
{
await VerifyBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""M"")>
Module M
Class C
End Class
End Module
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnMembers(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M1"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M3`1()"")]
public class C
{
int M1;
public void M2() {}
public static void M3<T>() {}
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") },
new[] { Diagnostic("Declaration", "M2") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task GlobalSuppressionOnValueTupleMemberWithDocId(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""~M:C.M~System.Threading.Tasks.Task{System.ValueTuple{System.Boolean,ErrorCode}}"")]
enum ErrorCode {}
class C
{
Task<(bool status, ErrorCode errorCode)> M() => null;
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MultipleGlobalSuppressionsOnSingleSymbol(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""TypeDeclaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("E"), new WarningOnTypeDeclarationAnalyzer() });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task DuplicateGlobalSuppressions(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
public class E
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") });
}
#endregion
#region Syntax Semantics
[Fact]
public async Task WarningOnCommentAnalyzerCSharp()
{
await VerifyCSharpAsync("// Comment\r\n /* Comment */",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// Comment"),
Diagnostic("Comment", "/* Comment */"));
}
[Fact]
public async Task WarningOnCommentAnalyzerBasic()
{
await VerifyBasicAsync("' Comment",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' Comment"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""C.Goo():System.Void"")]
// before class
public class C
{
// before method
public void Goo() // after method declaration
{
// inside method
}
}
// after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before class"),
Diagnostic("Comment", "// after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task GloballySuppressSyntaxDiagnosticsOnTargetBasic(string attrName)
{
await VerifyBasicAsync(@"
' before module attributes
<Module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Member"", Target:=""C.Goo():System.Void"")>
' before class
Public Class C
' before sub
Public Sub Goo() ' after sub statement
' inside sub
End Sub
End Class
' after class
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "' before module attributes"),
Diagnostic("Comment", "' before class"),
Diagnostic("Comment", "' after class"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""namespace"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "class").WithLocation(7, 9),
Diagnostic("Token", "C").WithLocation(7, 15),
Diagnostic("Token", "{").WithLocation(7, 17),
Diagnostic("Token", "}").WithLocation(7, 18),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndChildDeclarationCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
[assembly: " + attrName + @"(""Test"", ""Token"", Scope=""NamespaceAndDescendants"", Target=""A.B"")]
namespace A
[|{
namespace B
{
class C {}
}
}|]
",
Diagnostic("Token", "{").WithLocation(4, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""Namespace"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "Class").WithLocation(5, 9),
Diagnostic("Token", "C").WithLocation(5, 15),
Diagnostic("Token", "End").WithLocation(6, 9),
Diagnostic("Token", "Class").WithLocation(6, 13),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNamespaceAndDescendantsDeclarationBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
<assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""NamespaceAndDescendants"", Target:=""A.B"")>
Namespace [|A
Namespace B
Class C
End Class
End Namespace
End|] Namespace
",
Diagnostic("Token", "A").WithLocation(3, 11),
Diagnostic("Token", "End").WithLocation(8, 1));
}
[Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")]
[InlineData("Namespace")]
[InlineData("NamespaceAndDescendants")]
public async Task DontSuppressSyntaxDiagnosticsInRootNamespaceBasic(string scope)
{
await VerifyBasicAsync($@"
<module: System.Diagnostics.SuppressMessage(""Test"", ""Comment"", Scope:=""{scope}"", Target:=""RootNamespace"")>
' In root namespace
",
rootNamespace: "RootNamespace",
analyzers: new[] { new WarningOnCommentAnalyzer() },
diagnostics: Diagnostic("Comment", "' In root namespace").WithLocation(3, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
namespace N
[|{
[" + attrName + @"(""Test"", ""Token"")]
class C<T> {}
[" + attrName + @"(""Test"", ""Token"")]
struct S<T> {}
[" + attrName + @"(""Test"", ""Token"")]
interface I<T>{}
[" + attrName + @"(""Test"", ""Token"")]
enum E {}
[" + attrName + @"(""Test"", ""Token"")]
delegate void D();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(20, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnTypesBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Namespace [|N
<" + attrName + @"(""Test"", ""Token"")>
Module M
End Module
<" + attrName + @"(""Test"", ""Token"")>
Class C
End Class
<" + attrName + @"(""Test"", ""Token"")>
Structure S
End Structure
<" + attrName + @"(""Test"", ""Token"")>
Interface I
End Interface
<" + attrName + @"(""Test"", ""Token"")>
Enum E
None
End Enum
<" + attrName + @"(""Test"", ""Token"")>
Delegate Sub D()
End|] Namespace
",
Diagnostic("Token", "N").WithLocation(4, 11),
Diagnostic("Token", "End").WithLocation(28, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int field1 = 1, field2 = 2;
[" + attrName + @"(""Test"", ""Token"")]
int field3 = 3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEnumFieldsCSharp(string attrName)
{
await VerifyCSharpAsync(@"
// before module attributes
[module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""E.Field1"")]
// before enum
public enum E
{
// before Field1 declaration
Field1, // after Field1 declaration
Field2 // after Field2 declaration
}
// after enum
",
new[] { new WarningOnCommentAnalyzer() },
Diagnostic("Comment", "// before module attributes"),
Diagnostic("Comment", "// before enum"),
Diagnostic("Comment", "// after Field1 declaration"),
Diagnostic("Comment", "// after Field2 declaration"),
Diagnostic("Comment", "// after enum"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnFieldsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public field1 As Integer = 1,
field2 As Double = 2.0
<" + attrName + @"(""Test"", ""Token"")>
Public field3 As Integer = 3
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E1;
[" + attrName + @"(""Test"", ""Token"")]
public event System.Action<int> E2, E3;
}|]
",
Diagnostic("Token", "{"),
Diagnostic("Token", "}"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventsBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Event E1 As System.Action(Of Integer)
<" + attrName + @"(""Test"", ""Token"")>
Public Event E2(ByVal arg As Integer)
End|] Class
",
Diagnostic("Token", "C"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
[|{
[" + attrName + @"(""Test"", ""Token"")]
add {}
remove|] {}
}
}
",
Diagnostic("Token", "{").WithLocation(5, 5),
Diagnostic("Token", "remove").WithLocation(8, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer[|)
<" + attrName + @"(""Test"", ""Token"")>
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler|](value As Action(Of Integer))
End RemoveHandler
RaiseEvent(obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", ")"),
Diagnostic("Token", "RemoveHandler"));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
public event System.Action<int> E
{
add {[|}
[" + attrName + @"(""Test"", ""Token"")]
remove {}
}|]
}
",
Diagnostic("Token", "}").WithLocation(6, 14),
Diagnostic("Token", "}").WithLocation(9, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End [|AddHandler
<" + attrName + @"(""Test"", ""Token"")>
RemoveHandler(value As Action(Of Integer))
End RemoveHandler
RaiseEvent|](obj As Integer)
End RaiseEvent
End Event
End Class
",
Diagnostic("Token", "AddHandler"),
Diagnostic("Token", "RaiseEvent"));
}
[WorkItem(1103442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103442")]
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnRaiseEventAccessorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Public Custom Event E As System.Action(Of Integer)
AddHandler(value As Action(Of Integer))
End AddHandler
RemoveHandler(value As Action(Of Integer))
End [|RemoveHandler
<" + attrName + @"(""Test"", ""Token"")>
RaiseEvent(obj As Integer)
End RaiseEvent
End|] Event
End Class
",
Diagnostic("Token", "RemoveHandler"),
Diagnostic("Token", "End"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
int Property1 { get; set; }
[" + attrName + @"(""Test"", ""Token"")]
int Property2
{
get { return 2; }
set { Property1 = 2; }
}
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(15, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Property Property1 As Integer
<" + attrName + @"(""Test"", ""Token"")>
Property Property2 As Integer
Get
Return 2
End Get
Set(value As Integer)
Property1 = value
End Set
End Property
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 7),
Diagnostic("Token", "End").WithLocation(17, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertyGetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As [|Integer
<" + attrName + @"(""Test"", ""Token"")>
Get
Return 2
End Get
Set|](value As Integer)
x = value
End Set
End Property
End Class
",
Diagnostic("Token", "Integer").WithLocation(4, 28),
Diagnostic("Token", "Set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int Property
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnPropertySetterBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class C
Private x As Integer
Property [Property] As Integer
Get
Return 2
End [|Get
<" + attrName + @"(""Test"", ""Token"")>
Set(value As Integer)
x = value
End Set
End|] Property
End Class
",
Diagnostic("Token", "Get").WithLocation(7, 13),
Diagnostic("Token", "End").WithLocation(12, 5));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x[|;
[" + attrName + @"(""Test"", ""Token"")]
int this[int i]
{
get { return 2; }
set { x = 2; }
}
}|]
",
Diagnostic("Token", ";").WithLocation(4, 10),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerGetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
[|{
[" + attrName + @"(""Test"", ""Token"")]
get { return 2; }
set|] { x = 2; }
}
}
",
Diagnostic("Token", "{").WithLocation(6, 5),
Diagnostic("Token", "set").WithLocation(9, 9));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnIndexerSetterCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
{
int x;
int this[int i]
{
get { return 2; [|}
[" + attrName + @"(""Test"", ""Token"")]
set { x = 2; }
}|]
}
",
Diagnostic("Token", "}").WithLocation(7, 25),
Diagnostic("Token", "}").WithLocation(10, 5));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
abstract class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public void M1<T>() {}
[" + attrName + @"(""Test"", ""Token"")]
public abstract void M2();
}|]
",
Diagnostic("Token", "{").WithLocation(5, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnMethodBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
Public MustInherit Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Function M2(Of T)() As Integer
Return 0
End Function
<" + attrName + @"(""Test"", ""Token"")>
Public MustOverride Sub M3()
End|] Class
",
Diagnostic("Token", "C").WithLocation(4, 26),
Diagnostic("Token", "End").WithLocation(12, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
public static C operator +(C a, C b)
{
return null;
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(9, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnOperatorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Shared Operator +(ByVal a As C, ByVal b As C) As C
Return Nothing
End Operator
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(7, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class Base
{
public Base(int x) {}
}
class C : Base
[|{
[" + attrName + @"(""Test"", ""Token"")]
public C() : base(0) {}
}|]
",
Diagnostic("Token", "{").WithLocation(8, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnConstructorBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Public Sub New()
End Sub
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnDestructorCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
~C() {}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(6, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeCSharp(string attrName)
{
await VerifyTokenDiagnosticsCSharpAsync(@"
class C
[|{
[" + attrName + @"(""Test"", ""Token"")]
class D
{
class E
{
}
}
}|]
",
Diagnostic("Token", "{").WithLocation(3, 1),
Diagnostic("Token", "}").WithLocation(11, 1));
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressSyntaxDiagnosticsOnNestedTypeBasic(string attrName)
{
await VerifyTokenDiagnosticsBasicAsync(@"
Class [|C
<" + attrName + @"(""Test"", ""Token"")>
Class D
Class E
End Class
End Class
End|] Class
",
Diagnostic("Token", "C").WithLocation(2, 7),
Diagnostic("Token", "End").WithLocation(8, 1));
}
#endregion
#region Special Cases
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageCompilationEnded(string attrName)
{
await VerifyCSharpAsync(
@"[module: " + attrName + @"(""Test"", ""CompilationEnded"")]",
new[] { new WarningOnCompilationEndedAnalyzer() });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnPropertyAccessor(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
public string P { get; private set; }
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("get_") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnDelegateInvoke(string attrName)
{
await VerifyCSharpAsync(@"
public class C
{
[" + attrName + @"(""Test"", ""Declaration"")]
delegate void D();
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("Invoke") });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyCSharp(string attrName)
{
await VerifyCSharpAsync(
@"
public class C
{
[" + attrName + @"(""Test"", ""CodeBody"")]
void Goo()
{
Goo();
}
}
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.CSharp) });
}
[Theory]
[MemberData(nameof(QualifiedAttributeNames))]
public async Task SuppressMessageOnCodeBodyBasic(string attrName)
{
await VerifyBasicAsync(
@"
Public Class C
<" + attrName + @"(""Test"", ""CodeBody"")>
Sub Goo()
Goo()
End Sub
End Class
",
new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.VisualBasic) });
}
#endregion
#region Attribute Decoding
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task UnnecessaryScopeAndTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C1
{
}
[" + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
public class C2
{
}
[" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C"")]
public class C3
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") });
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""E"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task MissingScopeOrTarget(string attrName)
{
await VerifyCSharpAsync(@"
using System.Diagnostics.CodeAnalysis;
[module: " + attrName + @"(""Test"", ""Declaration"", Target=""C"")]
[module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")]
public class C
{
}
",
new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") },
Diagnostic("Declaration", "C"));
}
[Theory]
[MemberData(nameof(SimpleAttributeNames))]
public async Task InvalidAttributeConstructorParameters(string attrName)
{
await VerifyBasicAsync(@"
Imports System.Diagnostics.CodeAnalysis
<module: " + attrName + @"UndeclaredIdentifier, ""Comment"")>
<module: " + attrName + @"(""Test"", UndeclaredIdentifier)>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=UndeclaredIdentifier, Target:=""C"")>
<module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Type"", Target:=UndeclaredIdentifier)>
Class C
End Class
",
new[] { new WarningOnTypeDeclarationAnalyzer() },
Diagnostic("TypeDeclaration", "C").WithLocation(9, 7));
}
#endregion
protected async Task VerifyCSharpAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.CSharp, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsCSharpAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.CSharp, diagnostics);
}
protected async Task VerifyBasicAsync(string source, string rootNamespace, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
Assert.False(string.IsNullOrWhiteSpace(rootNamespace), string.Format("Invalid root namespace '{0}'", rootNamespace));
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics, rootNamespace: rootNamespace);
}
protected async Task VerifyBasicAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics)
{
await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics);
}
protected Task VerifyTokenDiagnosticsBasicAsync(string markup, params DiagnosticDescription[] diagnostics)
{
return VerifyTokenDiagnosticsAsync(markup, LanguageNames.VisualBasic, diagnostics);
}
protected abstract Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null);
// Generate a diagnostic on every token in the specified spans, and verify that only the specified diagnostics are not suppressed
private Task VerifyTokenDiagnosticsAsync(string markup, string language, DiagnosticDescription[] diagnostics)
{
MarkupTestFile.GetSpans(markup, out var source, out ImmutableArray<TextSpan> spans);
Assert.True(spans.Length > 0, "Must specify a span within which to generate diagnostics on each token");
return VerifyAsync(source, language, new DiagnosticAnalyzer[] { new WarningOnTokenAnalyzer(spans) }, diagnostics);
}
protected abstract bool ConsiderArgumentsForComparingDiagnostics { get; }
protected DiagnosticDescription Diagnostic(string id, string squiggledText)
{
var arguments = this.ConsiderArgumentsForComparingDiagnostics && squiggledText != null
? new[] { squiggledText }
: null;
return new DiagnosticDescription(id, false, squiggledText, arguments, null, null, false);
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/Core/Analyzers/ConvertAnonymousTypeToTuple/AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.ConvertAnonymousTypeToTuple
{
internal abstract class AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer<
TSyntaxKind,
TAnonymousObjectCreationExpressionSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TAnonymousObjectCreationExpressionSyntax : SyntaxNode
{
private readonly ISyntaxKinds _syntaxKinds;
protected AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer(ISyntaxKinds syntaxKinds)
: base(IDEDiagnosticIds.ConvertAnonymousTypeToTupleDiagnosticId,
EnforceOnBuildValues.ConvertAnonymousTypeToTuple,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
// This analyzer is not configurable. The intent is just to act as a refactoring, just benefiting from fix-all
configurable: false)
{
_syntaxKinds = syntaxKinds;
}
protected abstract int GetInitializerCount(TAnonymousObjectCreationExpressionSyntax anonymousType);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(
AnalyzeSyntax,
_syntaxKinds.Convert<TSyntaxKind>(_syntaxKinds.AnonymousObjectCreationExpression));
// Analysis is trivial. All anonymous types with more than two fields are marked as being
// convertible to a tuple.
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var anonymousType = (TAnonymousObjectCreationExpressionSyntax)context.Node;
if (GetInitializerCount(anonymousType) < 2)
{
return;
}
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Node.GetFirstToken().GetLocation(), ReportDiagnostic.Hidden,
additionalLocations: null, properties: 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 Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.ConvertAnonymousTypeToTuple
{
internal abstract class AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer<
TSyntaxKind,
TAnonymousObjectCreationExpressionSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TAnonymousObjectCreationExpressionSyntax : SyntaxNode
{
private readonly ISyntaxKinds _syntaxKinds;
protected AbstractConvertAnonymousTypeToTupleDiagnosticAnalyzer(ISyntaxKinds syntaxKinds)
: base(IDEDiagnosticIds.ConvertAnonymousTypeToTupleDiagnosticId,
EnforceOnBuildValues.ConvertAnonymousTypeToTuple,
option: null,
new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_tuple), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
// This analyzer is not configurable. The intent is just to act as a refactoring, just benefiting from fix-all
configurable: false)
{
_syntaxKinds = syntaxKinds;
}
protected abstract int GetInitializerCount(TAnonymousObjectCreationExpressionSyntax anonymousType);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(
AnalyzeSyntax,
_syntaxKinds.Convert<TSyntaxKind>(_syntaxKinds.AnonymousObjectCreationExpression));
// Analysis is trivial. All anonymous types with more than two fields are marked as being
// convertible to a tuple.
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var anonymousType = (TAnonymousObjectCreationExpressionSyntax)context.Node;
if (GetInitializerCount(anonymousType) < 2)
{
return;
}
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Node.GetFirstToken().GetLocation(), ReportDiagnostic.Hidden,
additionalLocations: null, properties: null));
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/ImplementerFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.FindSymbols;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.CallHierarchy;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders
{
internal class ImplementerFinder : AbstractCallFinder
{
public ImplementerFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider)
: base(symbol, projectId, asyncListener, provider)
{
}
public override string DisplayName
{
get
{
return string.Format(EditorFeaturesResources.Implements_0, SymbolName);
}
}
protected override Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken)
=> throw new NotImplementedException();
protected override async Task SearchWorkerAsync(ISymbol symbol, Project project, ICallHierarchySearchCallback callback, IImmutableSet<Document> documents, CancellationToken cancellationToken)
{
var implementations = await SymbolFinder.FindImplementationsAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
var sourceLocations = implementation.DeclaringSyntaxReferences.Select(d => project.Solution.GetDocument(d.SyntaxTree)).WhereNotNull();
var bestLocation = sourceLocations.FirstOrDefault(d => documents == null || documents.Contains(d));
if (bestLocation != null)
{
var item = await Provider.CreateItemAsync(implementation, bestLocation.Project, SpecializedCollections.EmptyEnumerable<Location>(), cancellationToken).ConfigureAwait(false);
callback.AddResult(item);
cancellationToken.ThrowIfCancellationRequested();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.FindSymbols;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.CallHierarchy;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders
{
internal class ImplementerFinder : AbstractCallFinder
{
public ImplementerFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider)
: base(symbol, projectId, asyncListener, provider)
{
}
public override string DisplayName
{
get
{
return string.Format(EditorFeaturesResources.Implements_0, SymbolName);
}
}
protected override Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken)
=> throw new NotImplementedException();
protected override async Task SearchWorkerAsync(ISymbol symbol, Project project, ICallHierarchySearchCallback callback, IImmutableSet<Document> documents, CancellationToken cancellationToken)
{
var implementations = await SymbolFinder.FindImplementationsAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
var sourceLocations = implementation.DeclaringSyntaxReferences.Select(d => project.Solution.GetDocument(d.SyntaxTree)).WhereNotNull();
var bestLocation = sourceLocations.FirstOrDefault(d => documents == null || documents.Contains(d));
if (bestLocation != null)
{
var item = await Provider.CreateItemAsync(implementation, bestLocation.Project, SpecializedCollections.EmptyEnumerable<Location>(), cancellationToken).ConfigureAwait(false);
callback.AddResult(item);
cancellationToken.ThrowIfCancellationRequested();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.CompositionEventSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.Editor.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class CompositionEventSource : ITaggerEventSource
{
private readonly ITaggerEventSource[] _providers;
public CompositionEventSource(ITaggerEventSource[] providers)
{
Contract.ThrowIfNull(providers);
_providers = providers;
}
public void Connect()
=> _providers.Do(p => p.Connect());
public void Disconnect()
=> _providers.Do(p => p.Disconnect());
public event EventHandler<TaggerEventArgs> Changed
{
add => _providers.Do(p => p.Changed += value);
remove => _providers.Do(p => p.Changed -= 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;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class CompositionEventSource : ITaggerEventSource
{
private readonly ITaggerEventSource[] _providers;
public CompositionEventSource(ITaggerEventSource[] providers)
{
Contract.ThrowIfNull(providers);
_providers = providers;
}
public void Connect()
=> _providers.Do(p => p.Connect());
public void Disconnect()
=> _providers.Do(p => p.Disconnect());
public event EventHandler<TaggerEventArgs> Changed
{
add => _providers.Do(p => p.Changed += value);
remove => _providers.Do(p => p.Changed -= value);
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/TestUtilities/DocumentationComments/AbstractXmlTagCompletionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments
{
[UseExportProvider]
public abstract class AbstractXmlTagCompletionTests
{
internal abstract IChainedCommandHandler<TypeCharCommandArgs> CreateCommandHandler(TestWorkspace testWorkspace);
protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup);
public void Verify(string initialMarkup, string expectedMarkup, char typeChar)
{
using (var workspace = CreateTestWorkspace(initialMarkup))
{
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
var commandHandler = CreateCommandHandler(workspace);
var args = new TypeCharCommandArgs(view, view.TextBuffer, typeChar);
var nextHandler = CreateInsertTextHandler(view, typeChar.ToString());
commandHandler.ExecuteCommand(args, nextHandler, TestCommandExecutionContext.Create());
MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition);
Assert.Equal(expectedCode, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
}
private static Action CreateInsertTextHandler(ITextView textView, string text)
{
return () =>
{
var caretPosition = textView.Caret.Position.BufferPosition;
var newSpanshot = textView.TextBuffer.Insert(caretPosition, text);
textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, caretPosition + text.Length));
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments
{
[UseExportProvider]
public abstract class AbstractXmlTagCompletionTests
{
internal abstract IChainedCommandHandler<TypeCharCommandArgs> CreateCommandHandler(TestWorkspace testWorkspace);
protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup);
public void Verify(string initialMarkup, string expectedMarkup, char typeChar)
{
using (var workspace = CreateTestWorkspace(initialMarkup))
{
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
var commandHandler = CreateCommandHandler(workspace);
var args = new TypeCharCommandArgs(view, view.TextBuffer, typeChar);
var nextHandler = CreateInsertTextHandler(view, typeChar.ToString());
commandHandler.ExecuteCommand(args, nextHandler, TestCommandExecutionContext.Create());
MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition);
Assert.Equal(expectedCode, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
}
private static Action CreateInsertTextHandler(ITextView textView, string text)
{
return () =>
{
var caretPosition = textView.Caret.Position.BufferPosition;
var newSpanshot = textView.TextBuffer.Insert(caretPosition, text);
textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, caretPosition + text.Length));
};
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Shared/Utilities/SemanticMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal partial class SemanticMap
{
private readonly Dictionary<SyntaxNode, SymbolInfo> _expressionToInfoMap =
new();
private readonly Dictionary<SyntaxToken, SymbolInfo> _tokenToInfoMap =
new();
private SemanticMap()
{
}
internal static SemanticMap From(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
{
var map = new SemanticMap();
var walker = new Walker(semanticModel, map, cancellationToken);
walker.Visit(node);
return map;
}
public IEnumerable<ISymbol> AllReferencedSymbols
{
get
{
return _expressionToInfoMap.Values.Concat(_tokenToInfoMap.Values).Select(info => info.Symbol).Distinct();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal partial class SemanticMap
{
private readonly Dictionary<SyntaxNode, SymbolInfo> _expressionToInfoMap =
new();
private readonly Dictionary<SyntaxToken, SymbolInfo> _tokenToInfoMap =
new();
private SemanticMap()
{
}
internal static SemanticMap From(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
{
var map = new SemanticMap();
var walker = new Walker(semanticModel, map, cancellationToken);
walker.Visit(node);
return map;
}
public IEnumerable<ISymbol> AllReferencedSymbols
{
get
{
return _expressionToInfoMap.Values.Concat(_tokenToInfoMap.Values).Select(info => info.Symbol).Distinct();
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/IdentifierNameSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal partial class IdentifierNameSyntax
{
public override string ToString()
{
return this.Identifier.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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal partial class IdentifierNameSyntax
{
public override string ToString()
{
return this.Identifier.Text;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Syntax/ParentChecker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public static class ParentChecker
{
public static void CheckParents(SyntaxNodeOrToken nodeOrToken, SyntaxTree expectedSyntaxTree)
{
Assert.Equal(expectedSyntaxTree, nodeOrToken.SyntaxTree);
var span = nodeOrToken.Span;
if (nodeOrToken.IsToken)
{
var token = nodeOrToken.AsToken();
foreach (var trivia in token.LeadingTrivia)
{
var tspan = trivia.Span;
var parentToken = trivia.Token;
Assert.Equal(parentToken, token);
if (trivia.HasStructure)
{
var parentTrivia = trivia.GetStructure().Parent;
Assert.Null(parentTrivia);
CheckParents((CSharpSyntaxNode)trivia.GetStructure(), expectedSyntaxTree);
}
}
foreach (var trivia in token.TrailingTrivia)
{
var tspan = trivia.Span;
var parentToken = trivia.Token;
Assert.Equal(parentToken, token);
if (trivia.HasStructure)
{
var parentTrivia = trivia.GetStructure().Parent;
Assert.Null(parentTrivia);
CheckParents(trivia.GetStructure(), expectedSyntaxTree);
}
}
}
else
{
var node = nodeOrToken.AsNode();
foreach (var child in node.ChildNodesAndTokens())
{
var parent = child.Parent;
Assert.Equal(node, parent);
CheckParents(child, expectedSyntaxTree);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public static class ParentChecker
{
public static void CheckParents(SyntaxNodeOrToken nodeOrToken, SyntaxTree expectedSyntaxTree)
{
Assert.Equal(expectedSyntaxTree, nodeOrToken.SyntaxTree);
var span = nodeOrToken.Span;
if (nodeOrToken.IsToken)
{
var token = nodeOrToken.AsToken();
foreach (var trivia in token.LeadingTrivia)
{
var tspan = trivia.Span;
var parentToken = trivia.Token;
Assert.Equal(parentToken, token);
if (trivia.HasStructure)
{
var parentTrivia = trivia.GetStructure().Parent;
Assert.Null(parentTrivia);
CheckParents((CSharpSyntaxNode)trivia.GetStructure(), expectedSyntaxTree);
}
}
foreach (var trivia in token.TrailingTrivia)
{
var tspan = trivia.Span;
var parentToken = trivia.Token;
Assert.Equal(parentToken, token);
if (trivia.HasStructure)
{
var parentTrivia = trivia.GetStructure().Parent;
Assert.Null(parentTrivia);
CheckParents(trivia.GetStructure(), expectedSyntaxTree);
}
}
}
else
{
var node = nodeOrToken.AsNode();
foreach (var child in node.ChildNodesAndTokens())
{
var parent = child.Parent;
Assert.Equal(node, parent);
CheckParents(child, expectedSyntaxTree);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Interactive/CommonVsUtils.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
// TODO (tomat): this needs to be polished and tested
internal static class CommonVsUtils
{
internal const string OutputWindowId = "34e76e81-ee4a-11d0-ae2e-00a0c90fffc3";
internal static string GetFilePath(ITextBuffer textBuffer)
{
if (textBuffer.Properties.TryGetProperty<ITextDocument>(typeof(ITextDocument), out var textDocument))
{
return textDocument.FilePath;
}
else
{
return null;
}
}
/// <summary>
/// Gets the current IWpfTextView that is the active document.
/// </summary>
/// <returns></returns>
public static IWpfTextView GetActiveTextView()
{
var monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection));
if (monitorSelection == null)
{
return null;
}
if (ErrorHandler.Failed(monitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var curDocument)))
{
// TODO: Report error
return null;
}
if (!(curDocument is IVsWindowFrame frame))
{
// TODO: Report error
return null;
}
if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out var docView)))
{
// TODO: Report error
return null;
}
if (docView is IVsCodeWindow)
{
if (ErrorHandler.Failed(((IVsCodeWindow)docView).GetPrimaryView(out var textView)))
{
// TODO: Report error
return null;
}
var model = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
var adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
var wpfTextView = adapterFactory.GetWpfTextView(textView);
return wpfTextView;
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
// TODO (tomat): this needs to be polished and tested
internal static class CommonVsUtils
{
internal const string OutputWindowId = "34e76e81-ee4a-11d0-ae2e-00a0c90fffc3";
internal static string GetFilePath(ITextBuffer textBuffer)
{
if (textBuffer.Properties.TryGetProperty<ITextDocument>(typeof(ITextDocument), out var textDocument))
{
return textDocument.FilePath;
}
else
{
return null;
}
}
/// <summary>
/// Gets the current IWpfTextView that is the active document.
/// </summary>
/// <returns></returns>
public static IWpfTextView GetActiveTextView()
{
var monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection));
if (monitorSelection == null)
{
return null;
}
if (ErrorHandler.Failed(monitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var curDocument)))
{
// TODO: Report error
return null;
}
if (!(curDocument is IVsWindowFrame frame))
{
// TODO: Report error
return null;
}
if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out var docView)))
{
// TODO: Report error
return null;
}
if (docView is IVsCodeWindow)
{
if (ErrorHandler.Failed(((IVsCodeWindow)docView).GetPrimaryView(out var textView)))
{
// TODO: Report error
return null;
}
var model = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
var adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
var wpfTextView = adapterFactory.GetWpfTextView(textView);
return wpfTextView;
}
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/Guids.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
// MUST match guids.h
using System;
namespace Roslyn.VisualStudio.DiagnosticsWindow
{
internal static class GuidList
{
public const string guidVisualStudioDiagnosticsWindowPkgString = "49e24138-9ee3-49e0-8ede-6b39f49303bf";
public const string guidVisualStudioDiagnosticsWindowCmdSetString = "f22c2499-790a-4b6c-b0fd-b6f0491e1c9c";
public const string guidToolWindowPersistanceString = "b2da68d7-fd1c-491a-a9a0-24f597b9f56c";
public static readonly Guid guidVisualStudioDiagnosticsWindowCmdSet = new Guid(guidVisualStudioDiagnosticsWindowCmdSetString);
};
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
// MUST match guids.h
using System;
namespace Roslyn.VisualStudio.DiagnosticsWindow
{
internal static class GuidList
{
public const string guidVisualStudioDiagnosticsWindowPkgString = "49e24138-9ee3-49e0-8ede-6b39f49303bf";
public const string guidVisualStudioDiagnosticsWindowCmdSetString = "f22c2499-790a-4b6c-b0fd-b6f0491e1c9c";
public const string guidToolWindowPersistanceString = "b2da68d7-fd1c-491a-a9a0-24f597b9f56c";
public static readonly Guid guidVisualStudioDiagnosticsWindowCmdSet = new Guid(guidVisualStudioDiagnosticsWindowCmdSetString);
};
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Emitter/Model/PEAssemblyBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEAssemblyBuilderBase : PEModuleBuilder, Cci.IAssemblyReference
{
private readonly SourceAssemblySymbol _sourceAssembly;
/// <summary>
/// Additional types injected by the Expression Evaluator.
/// </summary>
private readonly ImmutableArray<NamedTypeSymbol> _additionalTypes;
private ImmutableArray<Cci.IFileReference> _lazyFiles;
/// <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary>
private ImmutableArray<Cci.IFileReference> _lazyFilesWithoutManifestResources;
private SynthesizedEmbeddedAttributeSymbol _lazyEmbeddedAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsReadOnlyAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsByRefLikeAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsUnmanagedAttribute;
private SynthesizedEmbeddedNullableAttributeSymbol _lazyNullableAttribute;
private SynthesizedEmbeddedNullableContextAttributeSymbol _lazyNullableContextAttribute;
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol _lazyNullablePublicOnlyAttribute;
private SynthesizedEmbeddedNativeIntegerAttributeSymbol _lazyNativeIntegerAttribute;
/// <summary>
/// The behavior of the C# command-line compiler is as follows:
/// 1) If the /out switch is specified, then the explicit assembly name is used.
/// 2) Otherwise,
/// a) if the assembly is executable, then the assembly name is derived from
/// the name of the file containing the entrypoint;
/// b) otherwise, the assembly name is derived from the name of the first input
/// file.
///
/// Since we don't know which method is the entrypoint until well after the
/// SourceAssemblySymbol is created, in case 2a, its name will not reflect the
/// name of the file containing the entrypoint. We leave it to our caller to
/// provide that name explicitly.
/// </summary>
/// <remarks>
/// In cases 1 and 2b, we expect (metadataName == sourceAssembly.MetadataName).
/// </remarks>
private readonly string _metadataName;
public PEAssemblyBuilderBase(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources,
ImmutableArray<NamedTypeSymbol> additionalTypes)
: base((SourceModuleSymbol)sourceAssembly.Modules[0], emitOptions, outputKind, serializationProperties, manifestResources)
{
Debug.Assert(sourceAssembly is object);
_sourceAssembly = sourceAssembly;
_additionalTypes = additionalTypes.NullToEmpty();
_metadataName = (emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension: null);
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this);
}
public sealed override ISourceAssemblySymbolInternal SourceAssemblyOpt
=> _sourceAssembly;
public sealed override ImmutableArray<NamedTypeSymbol> GetAdditionalTopLevelTypes()
=> _additionalTypes;
internal sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance();
CreateEmbeddedAttributesIfNeeded(diagnostics);
builder.AddIfNotNull(_lazyEmbeddedAttribute);
builder.AddIfNotNull(_lazyIsReadOnlyAttribute);
builder.AddIfNotNull(_lazyIsUnmanagedAttribute);
builder.AddIfNotNull(_lazyIsByRefLikeAttribute);
builder.AddIfNotNull(_lazyNullableAttribute);
builder.AddIfNotNull(_lazyNullableContextAttribute);
builder.AddIfNotNull(_lazyNullablePublicOnlyAttribute);
builder.AddIfNotNull(_lazyNativeIntegerAttribute);
return builder.ToImmutableAndFree();
}
public sealed override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context)
{
if (!context.IsRefAssembly)
{
return getFiles(ref _lazyFiles);
}
return getFiles(ref _lazyFilesWithoutManifestResources);
ImmutableArray<Cci.IFileReference> getFiles(ref ImmutableArray<Cci.IFileReference> lazyFiles)
{
if (lazyFiles.IsDefault)
{
var builder = ArrayBuilder<Cci.IFileReference>.GetInstance();
try
{
var modules = _sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
builder.Add((Cci.IFileReference)Translate(modules[i], context.Diagnostics));
}
if (!context.IsRefAssembly)
{
// resources are not emitted into ref assemblies
foreach (ResourceDescription resource in ManifestResources)
{
if (!resource.IsEmbedded)
{
builder.Add(resource);
}
}
}
// Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed.
if (ImmutableInterlocked.InterlockedInitialize(ref lazyFiles, builder.ToImmutable()) && lazyFiles.Length > 0)
{
if (!CryptographicHashProvider.IsSupportedAlgorithm(_sourceAssembly.HashAlgorithm))
{
context.Diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_CryptoHashFailed), NoLocation.Singleton));
}
}
}
finally
{
builder.Free();
}
}
return lazyFiles;
}
}
protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics)
{
var modules = _sourceAssembly.Modules;
int count = modules.Length;
for (int i = 1; i < count; i++)
{
var file = (Cci.IFileReference)Translate(modules[i], diagnostics);
try
{
foreach (EmbeddedResource resource in ((Symbols.Metadata.PE.PEModuleSymbol)modules[i]).Module.GetEmbeddedResourcesOrThrow())
{
builder.Add(new Cci.ManagedResource(
resource.Name,
(resource.Attributes & ManifestResourceAttributes.Public) != 0,
null,
file,
resource.Offset));
}
}
catch (BadImageFormatException)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, modules[i]), NoLocation.Singleton);
}
}
}
public override string Name => _metadataName;
public AssemblyIdentity Identity => _sourceAssembly.Identity;
public Version AssemblyVersionPattern => _sourceAssembly.AssemblyVersionPattern;
internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute()
{
// _lazyEmbeddedAttribute should have been created before calling this method.
return new SynthesizedAttributeData(
_lazyEmbeddedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
internal override SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNullableAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableAttribute(member, arguments);
}
internal override SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableContextAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullableContextAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableContextAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullablePublicOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullablePublicOnlyAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullablePublicOnlyAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNativeIntegerAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNativeIntegerAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNativeIntegerAttribute(member, arguments);
}
protected override SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
if ((object)_lazyIsReadOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsReadOnlyAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsReadOnlyAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
if ((object)_lazyIsUnmanagedAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsUnmanagedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsUnmanagedAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
if ((object)_lazyIsByRefLikeAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsByRefLikeAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsByRefLikeAttribute();
}
private void CreateEmbeddedAttributesIfNeeded(BindingDiagnosticBag diagnostics)
{
EmbeddableAttributes needsAttributes = GetNeedsGeneratedAttributes();
if (ShouldEmitNullablePublicOnlyAttribute() &&
Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.NullablePublicOnlyAttribute, diagnostics, Location.None))
{
needsAttributes |= EmbeddableAttributes.NullablePublicOnlyAttribute;
}
else if (needsAttributes == 0)
{
return;
}
var createParameterlessEmbeddedAttributeSymbol = new Func<string, NamespaceSymbol, BindingDiagnosticBag, SynthesizedEmbeddedAttributeSymbol>(CreateParameterlessEmbeddedAttributeSymbol);
CreateAttributeIfNeeded(
ref _lazyEmbeddedAttribute,
diagnostics,
AttributeDescription.CodeAnalysisEmbeddedAttribute,
createParameterlessEmbeddedAttributeSymbol);
if ((needsAttributes & EmbeddableAttributes.IsReadOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsReadOnlyAttribute,
diagnostics,
AttributeDescription.IsReadOnlyAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsByRefLikeAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsByRefLikeAttribute,
diagnostics,
AttributeDescription.IsByRefLikeAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsUnmanagedAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsUnmanagedAttribute,
diagnostics,
AttributeDescription.IsUnmanagedAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableAttribute,
diagnostics,
AttributeDescription.NullableAttribute,
CreateNullableAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableContextAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableContextAttribute,
diagnostics,
AttributeDescription.NullableContextAttribute,
CreateNullableContextAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullablePublicOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullablePublicOnlyAttribute,
diagnostics,
AttributeDescription.NullablePublicOnlyAttribute,
CreateNullablePublicOnlyAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NativeIntegerAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNativeIntegerAttribute,
diagnostics,
AttributeDescription.NativeIntegerAttribute,
CreateNativeIntegerAttributeSymbol);
}
}
private SynthesizedEmbeddedAttributeSymbol CreateParameterlessEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedAttributeSymbol(
name,
containingNamespace,
SourceModule,
baseType: GetWellKnownType(WellKnownType.System_Attribute, diagnostics));
private SynthesizedEmbeddedNullableAttributeSymbol CreateNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullableContextAttributeSymbol CreateNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableContextAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol CreateNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private SynthesizedEmbeddedNativeIntegerAttributeSymbol CreateNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNativeIntegerAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private void CreateAttributeIfNeeded<T>(
ref T symbol,
BindingDiagnosticBag diagnostics,
AttributeDescription description,
Func<string, NamespaceSymbol, BindingDiagnosticBag, T> factory)
where T : SynthesizedEmbeddedAttributeSymbolBase
{
if (symbol is null)
{
AddDiagnosticsForExistingAttribute(description, diagnostics);
var containingNamespace = GetOrSynthesizeNamespace(description.Namespace);
symbol = factory(description.Name, containingNamespace, diagnostics);
Debug.Assert(symbol.Constructors.Length == description.Signatures.Length);
if (symbol.GetAttributeUsageInfo() != AttributeUsageInfo.Default)
{
EnsureAttributeUsageAttributeMembersAvailable(diagnostics);
}
AddSynthesizedDefinition(containingNamespace, symbol);
}
}
private void AddDiagnosticsForExistingAttribute(AttributeDescription description, BindingDiagnosticBag diagnostics)
{
var attributeMetadataName = MetadataTypeName.FromFullName(description.FullName);
var userDefinedAttribute = _sourceAssembly.SourceModule.LookupTopLevelMetadataType(ref attributeMetadataName);
Debug.Assert((object)userDefinedAttribute.ContainingModule == _sourceAssembly.SourceModule);
if (!(userDefinedAttribute is MissingMetadataTypeSymbol))
{
diagnostics.Add(ErrorCode.ERR_TypeReserved, userDefinedAttribute.Locations[0], description.FullName);
}
}
private NamespaceSymbol GetOrSynthesizeNamespace(string namespaceFullName)
{
var result = SourceModule.GlobalNamespace;
foreach (var partName in namespaceFullName.Split('.'))
{
var subnamespace = (NamespaceSymbol)result.GetMembers(partName).FirstOrDefault(m => m.Kind == SymbolKind.Namespace);
if (subnamespace == null)
{
subnamespace = new SynthesizedNamespaceSymbol(result, partName);
AddSynthesizedDefinition(result, subnamespace);
}
result = subnamespace;
}
return result;
}
private NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetWellKnownType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private NamedTypeSymbol GetSpecialType(SpecialType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetSpecialType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private void EnsureAttributeUsageAttributeMembersAvailable(BindingDiagnosticBag diagnostics)
{
var compilation = _sourceAssembly.DeclaringCompilation;
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__ctor, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__Inherited, diagnostics, Location.None);
}
}
#nullable enable
internal sealed class PEAssemblyBuilder : PEAssemblyBuilderBase
{
public PEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray<NamedTypeSymbol>.Empty)
{
}
public override EmitBaseline? PreviousGeneration => null;
public override SymbolChanges? EncSymbolChanges => null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEAssemblyBuilderBase : PEModuleBuilder, Cci.IAssemblyReference
{
private readonly SourceAssemblySymbol _sourceAssembly;
/// <summary>
/// Additional types injected by the Expression Evaluator.
/// </summary>
private readonly ImmutableArray<NamedTypeSymbol> _additionalTypes;
private ImmutableArray<Cci.IFileReference> _lazyFiles;
/// <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary>
private ImmutableArray<Cci.IFileReference> _lazyFilesWithoutManifestResources;
private SynthesizedEmbeddedAttributeSymbol _lazyEmbeddedAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsReadOnlyAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsByRefLikeAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsUnmanagedAttribute;
private SynthesizedEmbeddedNullableAttributeSymbol _lazyNullableAttribute;
private SynthesizedEmbeddedNullableContextAttributeSymbol _lazyNullableContextAttribute;
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol _lazyNullablePublicOnlyAttribute;
private SynthesizedEmbeddedNativeIntegerAttributeSymbol _lazyNativeIntegerAttribute;
/// <summary>
/// The behavior of the C# command-line compiler is as follows:
/// 1) If the /out switch is specified, then the explicit assembly name is used.
/// 2) Otherwise,
/// a) if the assembly is executable, then the assembly name is derived from
/// the name of the file containing the entrypoint;
/// b) otherwise, the assembly name is derived from the name of the first input
/// file.
///
/// Since we don't know which method is the entrypoint until well after the
/// SourceAssemblySymbol is created, in case 2a, its name will not reflect the
/// name of the file containing the entrypoint. We leave it to our caller to
/// provide that name explicitly.
/// </summary>
/// <remarks>
/// In cases 1 and 2b, we expect (metadataName == sourceAssembly.MetadataName).
/// </remarks>
private readonly string _metadataName;
public PEAssemblyBuilderBase(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources,
ImmutableArray<NamedTypeSymbol> additionalTypes)
: base((SourceModuleSymbol)sourceAssembly.Modules[0], emitOptions, outputKind, serializationProperties, manifestResources)
{
Debug.Assert(sourceAssembly is object);
_sourceAssembly = sourceAssembly;
_additionalTypes = additionalTypes.NullToEmpty();
_metadataName = (emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension: null);
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this);
}
public sealed override ISourceAssemblySymbolInternal SourceAssemblyOpt
=> _sourceAssembly;
public sealed override ImmutableArray<NamedTypeSymbol> GetAdditionalTopLevelTypes()
=> _additionalTypes;
internal sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance();
CreateEmbeddedAttributesIfNeeded(diagnostics);
builder.AddIfNotNull(_lazyEmbeddedAttribute);
builder.AddIfNotNull(_lazyIsReadOnlyAttribute);
builder.AddIfNotNull(_lazyIsUnmanagedAttribute);
builder.AddIfNotNull(_lazyIsByRefLikeAttribute);
builder.AddIfNotNull(_lazyNullableAttribute);
builder.AddIfNotNull(_lazyNullableContextAttribute);
builder.AddIfNotNull(_lazyNullablePublicOnlyAttribute);
builder.AddIfNotNull(_lazyNativeIntegerAttribute);
return builder.ToImmutableAndFree();
}
public sealed override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context)
{
if (!context.IsRefAssembly)
{
return getFiles(ref _lazyFiles);
}
return getFiles(ref _lazyFilesWithoutManifestResources);
ImmutableArray<Cci.IFileReference> getFiles(ref ImmutableArray<Cci.IFileReference> lazyFiles)
{
if (lazyFiles.IsDefault)
{
var builder = ArrayBuilder<Cci.IFileReference>.GetInstance();
try
{
var modules = _sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
builder.Add((Cci.IFileReference)Translate(modules[i], context.Diagnostics));
}
if (!context.IsRefAssembly)
{
// resources are not emitted into ref assemblies
foreach (ResourceDescription resource in ManifestResources)
{
if (!resource.IsEmbedded)
{
builder.Add(resource);
}
}
}
// Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed.
if (ImmutableInterlocked.InterlockedInitialize(ref lazyFiles, builder.ToImmutable()) && lazyFiles.Length > 0)
{
if (!CryptographicHashProvider.IsSupportedAlgorithm(_sourceAssembly.HashAlgorithm))
{
context.Diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_CryptoHashFailed), NoLocation.Singleton));
}
}
}
finally
{
builder.Free();
}
}
return lazyFiles;
}
}
protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics)
{
var modules = _sourceAssembly.Modules;
int count = modules.Length;
for (int i = 1; i < count; i++)
{
var file = (Cci.IFileReference)Translate(modules[i], diagnostics);
try
{
foreach (EmbeddedResource resource in ((Symbols.Metadata.PE.PEModuleSymbol)modules[i]).Module.GetEmbeddedResourcesOrThrow())
{
builder.Add(new Cci.ManagedResource(
resource.Name,
(resource.Attributes & ManifestResourceAttributes.Public) != 0,
null,
file,
resource.Offset));
}
}
catch (BadImageFormatException)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, modules[i]), NoLocation.Singleton);
}
}
}
public override string Name => _metadataName;
public AssemblyIdentity Identity => _sourceAssembly.Identity;
public Version AssemblyVersionPattern => _sourceAssembly.AssemblyVersionPattern;
internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute()
{
// _lazyEmbeddedAttribute should have been created before calling this method.
return new SynthesizedAttributeData(
_lazyEmbeddedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
internal override SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNullableAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableAttribute(member, arguments);
}
internal override SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableContextAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullableContextAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableContextAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullablePublicOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullablePublicOnlyAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullablePublicOnlyAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNativeIntegerAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNativeIntegerAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNativeIntegerAttribute(member, arguments);
}
protected override SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
if ((object)_lazyIsReadOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsReadOnlyAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsReadOnlyAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
if ((object)_lazyIsUnmanagedAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsUnmanagedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsUnmanagedAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
if ((object)_lazyIsByRefLikeAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsByRefLikeAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsByRefLikeAttribute();
}
private void CreateEmbeddedAttributesIfNeeded(BindingDiagnosticBag diagnostics)
{
EmbeddableAttributes needsAttributes = GetNeedsGeneratedAttributes();
if (ShouldEmitNullablePublicOnlyAttribute() &&
Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.NullablePublicOnlyAttribute, diagnostics, Location.None))
{
needsAttributes |= EmbeddableAttributes.NullablePublicOnlyAttribute;
}
else if (needsAttributes == 0)
{
return;
}
var createParameterlessEmbeddedAttributeSymbol = new Func<string, NamespaceSymbol, BindingDiagnosticBag, SynthesizedEmbeddedAttributeSymbol>(CreateParameterlessEmbeddedAttributeSymbol);
CreateAttributeIfNeeded(
ref _lazyEmbeddedAttribute,
diagnostics,
AttributeDescription.CodeAnalysisEmbeddedAttribute,
createParameterlessEmbeddedAttributeSymbol);
if ((needsAttributes & EmbeddableAttributes.IsReadOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsReadOnlyAttribute,
diagnostics,
AttributeDescription.IsReadOnlyAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsByRefLikeAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsByRefLikeAttribute,
diagnostics,
AttributeDescription.IsByRefLikeAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsUnmanagedAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsUnmanagedAttribute,
diagnostics,
AttributeDescription.IsUnmanagedAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableAttribute,
diagnostics,
AttributeDescription.NullableAttribute,
CreateNullableAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableContextAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableContextAttribute,
diagnostics,
AttributeDescription.NullableContextAttribute,
CreateNullableContextAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullablePublicOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullablePublicOnlyAttribute,
diagnostics,
AttributeDescription.NullablePublicOnlyAttribute,
CreateNullablePublicOnlyAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NativeIntegerAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNativeIntegerAttribute,
diagnostics,
AttributeDescription.NativeIntegerAttribute,
CreateNativeIntegerAttributeSymbol);
}
}
private SynthesizedEmbeddedAttributeSymbol CreateParameterlessEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedAttributeSymbol(
name,
containingNamespace,
SourceModule,
baseType: GetWellKnownType(WellKnownType.System_Attribute, diagnostics));
private SynthesizedEmbeddedNullableAttributeSymbol CreateNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullableContextAttributeSymbol CreateNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableContextAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol CreateNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private SynthesizedEmbeddedNativeIntegerAttributeSymbol CreateNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNativeIntegerAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private void CreateAttributeIfNeeded<T>(
ref T symbol,
BindingDiagnosticBag diagnostics,
AttributeDescription description,
Func<string, NamespaceSymbol, BindingDiagnosticBag, T> factory)
where T : SynthesizedEmbeddedAttributeSymbolBase
{
if (symbol is null)
{
AddDiagnosticsForExistingAttribute(description, diagnostics);
var containingNamespace = GetOrSynthesizeNamespace(description.Namespace);
symbol = factory(description.Name, containingNamespace, diagnostics);
Debug.Assert(symbol.Constructors.Length == description.Signatures.Length);
if (symbol.GetAttributeUsageInfo() != AttributeUsageInfo.Default)
{
EnsureAttributeUsageAttributeMembersAvailable(diagnostics);
}
AddSynthesizedDefinition(containingNamespace, symbol);
}
}
private void AddDiagnosticsForExistingAttribute(AttributeDescription description, BindingDiagnosticBag diagnostics)
{
var attributeMetadataName = MetadataTypeName.FromFullName(description.FullName);
var userDefinedAttribute = _sourceAssembly.SourceModule.LookupTopLevelMetadataType(ref attributeMetadataName);
Debug.Assert((object)userDefinedAttribute.ContainingModule == _sourceAssembly.SourceModule);
if (!(userDefinedAttribute is MissingMetadataTypeSymbol))
{
diagnostics.Add(ErrorCode.ERR_TypeReserved, userDefinedAttribute.Locations[0], description.FullName);
}
}
private NamespaceSymbol GetOrSynthesizeNamespace(string namespaceFullName)
{
var result = SourceModule.GlobalNamespace;
foreach (var partName in namespaceFullName.Split('.'))
{
var subnamespace = (NamespaceSymbol)result.GetMembers(partName).FirstOrDefault(m => m.Kind == SymbolKind.Namespace);
if (subnamespace == null)
{
subnamespace = new SynthesizedNamespaceSymbol(result, partName);
AddSynthesizedDefinition(result, subnamespace);
}
result = subnamespace;
}
return result;
}
private NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetWellKnownType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private NamedTypeSymbol GetSpecialType(SpecialType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetSpecialType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private void EnsureAttributeUsageAttributeMembersAvailable(BindingDiagnosticBag diagnostics)
{
var compilation = _sourceAssembly.DeclaringCompilation;
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__ctor, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__Inherited, diagnostics, Location.None);
}
}
#nullable enable
internal sealed class PEAssemblyBuilder : PEAssemblyBuilderBase
{
public PEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray<NamedTypeSymbol>.Empty)
{
}
public override EmitBaseline? PreviousGeneration => null;
public override SymbolChanges? EncSymbolChanges => null;
}
}
| -1 |
dotnet/roslyn | 55,022 | Fix 'sync namespace' with file scoped namespaces | Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-21T19:13:03Z | 2021-07-26T19:25:07Z | 1453f20221fbd626b5195bf0c8653078e53f292e | 5e956729df67fdd6610253b05e1a232fe595af73 | Fix 'sync namespace' with file scoped namespaces. Fixes #54749
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActionSetPriority.cs | // Licensed to the .NET Foundation under one or more 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.UnifiedSuggestions
{
/// <summary>
/// Equivalent to SuggestedActionSetPriority, but in a location that can be used
/// by both local Roslyn and LSP.
/// </summary>
internal enum UnifiedSuggestedActionSetPriority
{
Lowest = 0, // Corresponds to SuggestedActionSetPriority.None
Low = 1,
Medium = 2,
High = 3
}
}
| // Licensed to the .NET Foundation under one or more 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.UnifiedSuggestions
{
/// <summary>
/// Equivalent to SuggestedActionSetPriority, but in a location that can be used
/// by both local Roslyn and LSP.
/// </summary>
internal enum UnifiedSuggestedActionSetPriority
{
Lowest = 0, // Corresponds to SuggestedActionSetPriority.None
Low = 1,
Medium = 2,
High = 3
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.